I want to add CORS to my server.
I have configured my nginx according to this: https://michielkalkman.com/snippets/nginx-cors-open-configuration.html
It seems to work fine when the server returns 200.
However, if the server returns something else, like 400 when the request is wrong, or 500 if internal error, the browser shows the No 'Access-Control-Allow-Origin' header
instead of reaching the error handler like it should.
What configuration am I missing to make it work?
Cross-Origin Resource Sharing (CORS) errors occur when a server doesn't return the HTTP headers required by the CORS standard. To resolve a CORS error from an API Gateway REST API or HTTP API, you must reconfigure the API to meet the CORS standard.
Open a network tab in your console. In the response header look for the Access-Control-Allow-Origin header. If it does not exist then add it as a middleware in the way we discussed above. If it does exist then make sure there is no URL mismatch with the website.
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.
Since version 1.7.5 you can use the always
keyword to return the headers regardless of the response code:
add_header 'Access-Control-Allow-Origin' '*' always;
http://nginx.org/en/docs/http/ngx_http_headers_module.html#add_header
This has been answered before: https://serverfault.com/questions/431274/nginx-services-fails-for-cross-domain-requests-if-the-service-returns-error.
add-header
doesn't work with HTTP errors, but the optional headers_more module can be used to workaround this limitation.
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