I have this configuration in my Nginx
server {
listen 8080;
add_header Access-Control-Allow-Origin *;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Content-Type';
}
Now I have my web application which does GET
and POST
for GET
It works fine but if I do Ajax POST
I get this error
XMLHttpRequest cannot load 'URL' . Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'Origin' is therefore not allowed access. The response had HTTP status code 404.
If I do a 'GET' request I can see this in my response.
Access-Control-Allow-Headers:Content-Type
Access-Control-Allow-Methods:GET, POST, OPTIONS
Access-Control-Allow-Origin:*
But if I make a post I don't see any of that.
To enable CORS on NGINX, you need to use the add_header directive and add it to the appropriate NGINX configuration file. to allow access from any domain.
If the server is under your control, add the origin of the requesting site to the set of domains permitted access by adding it to the Access-Control-Allow-Origin header's value. You can also configure a site to allow any site to access it by using the * wildcard. You should only use this for public APIs.
This happens if you haven't set up CORS configuration correctly. you can fix this on you'r local machine using a plugin/extension called Allow-Control-Allow-Origin and add you'r localhost into it. The other way is to manually fix the configuration in server side.
I had the same issue and got it solve by adding the keyword always
to my add_header
directive. As stated by the documentation:
add_header
: Adds the specified field to a response header provided that the response code equals 200, 201, 204, 206, 301, 302, 303, 304, or 307. [...]If the
always
parameter is specified (1.7.5), the header field will be added regardless of the response code.
What was happening is that, without always
, my GET
request were returned 200
and thus had the expected headers, while my POST
was getting a 400, thus without the headers and thus triggering CORS errors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With