Angular 7 CORS同时提供错误和数据

时间:2019-04-23 11:06:04

标签: javascript node.js angular express cors

我的应用程序前端位于angular 7中,后端位于ndoejs(快速)中。我正在nodejs server.js中使用cors模块,

var cors = require('cors')

app.use(cors());

当我从前端进行api调用时,在搜索了一些解决方案后,我又看到了OPTIONS的另一个调用,我发现OPTIONS是在进行cors调用的情况下是自动调用。

在我的情况下,两个命中都是OPTIONS,第二个是POST。 OPTIONS命中返回204 no content,而POST命中返回预期数据,但与此同时,我在浏览器中收到此错误。

Access to XMLHttpRequest at 'http://localhost:2233/api/question' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我的代码在try catch中,并且在api调用后进入catch,但是在网络标签中,api响应中可见数据。

有什么想法吗?

编辑

OPTIONS调用上的响应标头

Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, 
Authorization, Accept, Client-Security-Token, Accept-Encoding
Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, PATCH
Access-Control-Allow-Origin: *
Allow: POST
Connection: keep-alive
Content-Length: 4
Content-Type: text/html; charset=utf-8
Date: Tue, 23 Apr 2019 11:49:11 GMT
ETag: W/"4-Yf+Bwwqjx254r+pisuO9HfpJ6FQ"
Vary: Accept-Encoding
X-Powered-By: Express

POST呼叫时的响应标头

Connection: keep-alive
Content-Length: 64
Content-Type: application/json; charset=utf-8
Date: Tue, 23 Apr 2019 11:23:06 GMT
ETag: W/"40-q2QpyVWh4SyAq38SeUHizD/aESI"
Vary: X-HTTP-Method-Override, Accept-Encoding
X-Powered-By: Express

1 个答案:

答案 0 :(得分:0)

首先感谢Jaromanda X告诉我实际问题。

实际上问题不是在POST调用中获得cors响应标头,并且在搜索了一些问题之后,我才知道我的问题是在定义api路由之后并在移动cors()之后在应用程序中添加了cors()路线解决了这个问题。

相关问题