Ad

Angular 7 CORS Giving Error And Data At Same Time

My application front end is in angular 7 and backend is in ndoejs (express). I am using cors module in nodejs server.js like this.

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.

In my case both hits are there one is of OPTIONS and second is of 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.

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.

Any idea whats wrong??

EDIT

Response headers on OPTIONS call

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

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
Ad

Answer

First of all Thanks a ton to Jaromanda X for telling me the actual issue.

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.

Ad
source: stackoverflow.com
Ad