简体   繁体   English

Angular 7 CORS同时给出错误和数据

[英]Angular 7 CORS giving error and data at same time

My application front end is in angular 7 and backend is in ndoejs (express). 我的应用程序前端是角度7,后端是ndoejs(快速)。 I am using cors module in nodejs server.js like this. 我在nodejs server.js中使用cors模块。

var cors = require('cors')

app.use(cors());

When i am making api call from front end i can see one more call of OPTIONS after searching some solutions i found that OPTIONS is automatic call in case of cors calls. 当我从前端进行api呼叫时,我可以在搜索一些解决方案之后看到OPTIONS另一个呼叫,我发现OPTIONS是在cors呼叫的情况下自动呼叫。

In my case both hits are there one is of OPTIONS and second is of POST. 在我的情况下,两个命中都有一个是OPTIONS,第二个是POST。 OPTIONS hit returning 204 no content and POST hit is returning expected data but at the same time i am getting this error in my browser. 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.

My code is in try catch and its going in catch after api call but in network tab data is visible in api response. 我的代码是在try catch中,它在api调用后进入catch,但在网络选项卡中数据在api响应中可见。

Any idea whats wrong?? 任何想法都错了?

EDIT 编辑

Response headers on OPTIONS call 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

Response headers on POST call 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

First of all Thanks a ton to Jaromanda X for telling me the actual issue. 首先感谢Jaromanda X告诉我实际问题。

Actually issue was not getting cors response header in POST call and after googling some problems i came to know the problem that i was adding cors() in my application after defining api routes and after shifting cors() before routes solved the problem. 实际上问题是没有在POST调用中得到cors响应标题,并且在谷歌搜索一些问题之后我开始知道在定义api路由之后我在我的应用程序中添加cors()以及在路由解决问题之前转换cors()之后的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM