首页 文章

OPTIONS请求成功后,由于缺少CORS头,Angular 4请求失败

提问于
浏览
2

我遇到以下问题:在预检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

响应 Headers

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'访问 .

1 回答

  • 2

    我注意到Angular 6,OPTIONS请求启动了POST操作!

    在后端实现OPTIONS处理程序后,它返回200状态,看起来更好 .

    在OPTIONS请求中还有一个“预检请求”:Access-Control-Request-Headers:content-type .

    (文档引用:“在发出预检请求时,使用Access-Control-Request-Headers请求标头,让服务器知道在实际请求发生时将使用哪些HTTP标头 . ”)

    我通过允许内容类型(在后端REST服务器中)修复了这个问题: - “Access-Control-Allow-Headers”=>'Origin,Content-Type,X-Auth-Token,content-type'

    当然:“Access-Control-Allow-Origin”=>'*'

    然后,我得到了一个GET和POST工作!

相关问题