Any rails developer who writes an API will counter the problem regarding the Cors. For those who don't know, CORS (Cross-origin resource sharing) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain.
While using Nginx and Rails gem Rack-cors, chances are high you are getting a problem of duplicate response header values.
Access-Control-Allow-Origin
It refers to the origin from where the request is made and the asterisk shows, it allows a response from any domain.
Access-Control-Allow-Origin: *
It is allowed only at once in the response header. As The CORS spec explicitly states:
“ If the response includes zero or more than one Access-Control-Allow-Origin header value, return fail and terminate this algorithm. ”
What is the problem?
Access-Control-Allow-Origin is provided by both Rails rack-cors and Nginx. The problem occurs when Nginx provides a configuration that doesn’t override the one provided by Rails and gets duplicated.
It shows the error like,
“Access to XMLHttpRequest at (…) from the origin (…) has been blocked by CORS policy. The header contains multiple values ‘*, *’, but only one is allowed.”
And you get Response Headers values duplicated such as,
Then you are on the right way to solving the problem.
Solution:
Both Rails rack-cors and Nginx provides a way to setting up the access Access-Control-Allow-Origin. There is nothing crossed which overcomes this problem of not overriding the values.
There can be many solutions you can opt for but there is one which I recommend is only to set up response header from rails using rack-cors gem. And commenting the response headers from the Nginx configuration file.
Because rails rack-cors can come in handy in making changes instead of Nginx configuration.
Top comments (0)