跨域AJAX preflighting没有产地检查产地、跨域、AJAX、preflighting

2023-09-10 16:40:14 作者:逗比大神舍我其谁

似乎这不工作:

$.ajax({
    url:      "http://localhost:3000/foo.json",
    data:     { foo: 'bar' },
    headers:  { 'HTTP_X_CUSTOMHEADER': 'foobar' },
    xhrFields: { withCredentials: true }
});

在我上的jsfiddle运行它,一个选项的要求(根据浏览器的调试工具)触发了,看起来是这样的:

When I run it on jsfiddle, an OPTIONS request (according to the Chrome debug tools) fires off that looks like this:

Access-Control-Request-Headers: Origin, HTTP_X_CUSTOMHEADER, Accept
Access-Control-Request-Method:  GET
Origin:                         http://fiddle.jshell.net

然后(根据浏览器的调试工具),我的本地服务器返回以下标题:

And then (according to the Chrome debug tools) my local server returns the following headers:

(手动重新格式化为可读性)的

Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers:     HTTP_X_CUSTOMHEADER
Access-Control-Allow-Methods:     GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:      http://fiddle.jshell.net
Access-Control-Max-Age:           10

Cache-Control:                    no-cache
Connection:                       Keep-Alive
Content-Length:                   1
Content-Type:                     text/html; charset=utf-8
Date:                             Wed, 14 Sep 2011 22:42:28 GMT
Server:                           WEBrick/1.3.1 (Ruby/1.8.7/2010-01-10)
X-Runtime:                        2

然后在控制台中我得到这样一个错误信息:

And then in the console I get an error message like this:

XMLHttpRequest cannot load http://localhost:3000/foo.json?foo=bar.
Origin http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin.

访问控制 - 允许 - 原产地标题出现相同的,当我的服务器,以preflight的请求做出了回应。所以我错过了什么一块在这里的这个难题?

But the Access-Control-Allow-Origin header appears identical to when my server responded with to the preflight request. So what piece am I missing here of this puzzle?

推荐答案

OHHHHH,确定我想通了这一点,最后...

OHHHHH, ok I figured this out, finally...

显然,preflight 选项响应头的arent需要它们的地方。您需要包括实际内容的响应这些头为好。我只有这些头下来在preflight,以为那就是唯一需要的入场券。

Apparently the preflight OPTIONS response headers arent the only place that needs them. You need to include those headers on the response for the actual content as well. I only had these headers coming down on the preflight, thinking that was the only "ticket" needed.

所以我加入了同一个标题为实际资产的GET请求和现在的一切的伟大工程。我想我错过了在该文档。

So I added the same headers to the GET request for the actual asset and everything works great now. I guess I missed that in the docs.