Issue
I am currently working on an app made with Angular 2 and an API made with Express. I'm struggling to make my Http request from Angular work as I receive CORS errors. I have two different problems in two different environment (but I think if I understand what I miss I could correct both)
First here is how are managed CORS in Express:
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, Access-Control-Allow-Credentials");
res.header("Access-Control-Allow-Credentials", "true");
and here the post request in Angular:
this.http.post(Constants.SEND_MAIL, {body1, body2, body3})
.map(
(response: Response) => {
console.log(response.json())
return response.json()
}
)
Here is environment which cause me troubles:
My webapp and API both run locally
When I am making a post request I get the following error:
Access to XMLHttpRequest at 'http://localhost:3000/api/data' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
When I start the Angular app, I use a proxy.con.json file:
"/api/data": {
"target": "http://localhost:3000/",
"secure": false
}
which I call with:
ng serve --port 4200 --proxy-config proxy.conf.json --environment=local
Angular app run locally, and Express on my development NGINX server
This time, the request is pending for a while, and then I get the following error:
Access to XMLHttpRequest at 'https://exemple.com/api/data' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
But this time it only doesn't work for this particular route. All others route are working fine.
I am just beginning with Angular, so I think I may miss something important on how are handled CORS.
Solution
The error message says that the problem is with the response to the preflight OPTIONS request.
You haven't provided a mcve but I'm going to assume that you are putting those headers on in the code for the endpoint for the POST request.
You need an endpoint for options
and post
and both need to provide CORS headers.
Throw away the code you've written to handle CORS. You've reinvented the wheel and made one that doesn't work.
Use the cors
module from npm which provides middleware that will handle CORS for you - on preflight and final requests.
Ensure that you:
- Register the middleware before you register your endpoint (because Express tests them in order)
- Follow the documentation for using the module with preflight requests.
Answered By - Quentin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.