CORS请求立即取消chrome

CORS request immediately canceled chrome

本文关键字:取消 chrome 请求 CORS      更新时间:2023-09-26

我试图通过AJAX发送一个文件到rackspace。这是我第一次看CORS。我在文档中看到了发送预飞行请求的选项,但是因为我自己设置了标题,并且知道我的origin是有效的,所以我试图放弃,这些是来自我的上传端点的标题:

HTTP/1.1 204 No Content
Content-Length: 0
X-Container-Object-Count: 2
Accept-Ranges: bytes
X-Container-Meta-Access-Log-Delivery: false
X-Container-Meta-Access-Control-Expose-Headers: etag location x-timestamp x-trans-id
X-Timestamp: 1401852621.29287
X-Container-Meta-Access-Control-Allow-Origin: h ttp://localhost:8080**<-- (manually added the space after "h" so stackoverflow would let me submit) 
X-Container-Bytes-Used: 5572910
Content-Type: text/plain; charset=utf-8
X-Trans-Id: txfc64055cb1114b6fb0ef6-0053a77a46ord1
Date: Mon, 23 Jun 2014 00:52:22 GMT

然而,每当我尝试发送请求时,它立即在chrome中失败,显示以下消息:

XMLHttpRequest cannot load [**I'm redacting my actual endpoint**]. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'h ttp://localhost:8080' is therefore not allowed access. 

这是我的请求头:

Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryZSg4nEq8EDaXQQBu
Origin:h ttp://localhost:8080
Referer:h ttp://localhost:8080/tools/artwork
<-- (manually added the space after "h" so stackoverflow would let me submit) 
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36

我错过了什么?即使你知道出发地是允许的,也需要飞行前申请吗?我从来没有看到一个数据包返回似乎Chrome没有发送?

是的,任何时候您的CORS请求不是"简单"的类型都需要预飞行-意思是,您有除GET, HEAD或POST之外的方法,除application/x-www-form-urlencoded, multipart/form-data或text/plain之外的内容类型,或者您的请求设置自定义标头。

无论如何,您粘贴的响应首先不包含Access-Control-Allow-Origin(它有X-Container-Meta-Access-Control-Allow-Origin),这就是您的请求被拒绝的原因。

在您的服务器中添加Access-Control-Allow-Origin: http://foo.example标头。

例如在Spring Controller中,response.setHeader("Access-Control-Allow-Origin", "http:localhost:8080");

附加内容,

Access-Control-Allow-Origin: http://foo.example   // you can add as many urls separated by commas or '*' to allow all urs
Access-Control-Allow-Methods: POST, GET, OPTIONS // Request method options separated by commas
Access-Control-Allow-Headers: X-PINGOTHER
Access-Control-Max-Age: 1728000      // expiration in milliseconds

参考此MDN站点