我遇到以下问题:在预检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” 访问。
答案 0 :(得分:2)
我注意到在Angular 6中,POST操作是由OPTIONS请求启动的!
在后端实现了OPTIONS处理程序后,该处理程序返回了200个状态,看起来更好。
在OPTIONS请求中,还有一个“预检请求”:Access-Control-Request-Headers:content-type。
(文档引用:“在发出预检请求时使用Access-Control-Request-Headers请求标头,以使服务器知道在发出实际请求时将使用哪些HTTP标头。”
我通过允许内容类型(在后端REST服务器中)来解决此问题:-“ Access-Control-Allow-Headers” =>'来源,内容类型,X-Auth-Token,内容类型'< / p>
当然:“ Access-Control-Allow-Origin” =>'*'
然后,我进行了GET和POST!