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

标签 angular cors

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

响应 header

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

错误信息

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

最佳答案

我注意到 Angular 6 中的 POST 操作是由 OPTIONS 请求启动的!

在后端实现 OPTIONS 处理程序后,返回 200 状态,看起来好多了。

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

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

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

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

然后,我的 GET 和 POST 工作正常了!

关于OPTIONS 请求成功后,由于缺少 CORS header ,Angular 4 请求失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46649806/

相关文章:

Angular *ngFor 用组项创建表?

javascript - Angularjs 跨源资源共享 (CORS) post 或 put 方法在 IE8 和 IE9 中不起作用

node.js - nginx 反向代理设置在执行 CORS 请求时不保留 session ID

javascript - Express.js CORS配置,PUT不起作用?

angular - 当 FormArray 为空时 FormArray 应该无效

angular - 如何使用选择快照?

Angular 4 typescript 解析响应对象中的枚举接口(interface)属性

aws-lambda - 在 AWS APIGW 和 Lambda 处理程序上管理 CORS

javascript - 如何防止在 Chrome 中发送 Origin HTTP header ?

typescript - Angular2 组件未呈现