【发布时间】:2018-03-20 20:40:18
【问题描述】:
我遇到以下问题:预检 OPTIONS 请求成功后,后续 POST 请求失败。这有点违反直觉,因为一旦 OPTIONS 成功,就应该接受后续请求。
流程如下:
Request URL:https://<my aws hosted api endpoint>/pchacin/calc/sum
Request Method:OPTIONS
authority:<my aws end point>
method:OPTIONS
path:/pchacin/calc/sum
scheme:https
accept:*/*
accept-encoding:gzip, deflate, br
accept-language:ca,en;q=0.8,en-US;q=0.6,es-ES;q=0.4,es;q=0.2
access-control-request-headers:authorization,content-type
access-control-request-method:POST
origin:http://localhost:4200
referer:http://localhost:4200/calculator/sum
响应标头
Status Code:200
access-control-allow-credentials:true
access-control-allow-headers:Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent
access-control-allow-methods:OPTIONS,POST
access-control-allow-origin:*
content-length:0
content-type:application/json
发布请求
Request URL:https://<my amazon end point>/pchacin/calc/sum
Request Method:POST
method:POST
path:/pchacin/calc/sum
scheme:https
accept:application/json, text/plain, */*
accept-encoding:gzip, deflate, br
accept-language:ca,en;q=0.8,en-US;q=0.6,es-ES;q=0.4,es;q=0.2
authorization: <my security token>
content-length:13
content-type:application/json
origin:http://localhost:4200
referer:http://localhost:4200/calculator/sum
user-agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100
Safari/537.36
发布响应(通知是返回200,我实际上看到了结果内容,所以后端可以接受请求)
content-length:12
content-type:application/json
date:Mon, 09 Oct 2017 14:25:29 GMT .
status:200
错误信息
请求中没有“Access-Control-Allow-Origin”标头 资源。因此不允许使用原点“http://localhost:4200” 访问。
【问题讨论】:
-
您需要将服务器配置为使用匹配的
Access-Control-Allow-Origin标头进行响应,否则浏览器将拒绝发出实际请求。 Angular 对此无能为力。 -
@GünterZöchbauer 我在 OPTIONS 方法中做到了这一点,但从证据来看,这是需要标头的实际 POST 请求。据我了解,这不是protocol says。
-
如果服务器没有返回错误响应,则 OPTIONS 请求始终成功,但如果没有返回标头,浏览器甚至不会发送实际请求。显然返回的标头与浏览器的期望不符。
-
AFAIR 如果
credentials:true被使用*不被Access-Control-Allow-Origin接受。从请求中获取他的来源并在服务器上返回这个而不是*,或者如果事先知道,则添加一个静态 URL。 -
您对 CORS 协议的理解不正确——对 POST 请求的响应还必须有一个 Access-Control-Allow-Origin 标头,因为为了让浏览器允许您的前端代码访问any 来自任何跨域请求的响应,响应必须具有 Access-Control-Allow-Origin。如果您包含凭据,则 Access-Control-Allow-Origin 的值不能是
*通配符;相反,该值必须是单一来源。因此,在这种情况下,您需要将服务器配置为返回实际的原始值:Access-Control-Allow-Origin: http://localhost:4200/