Origin is not allowed by Access-Control-Allow-Origin
"Origin is not allowed by Access-Control-Allow-Origin" error, it's like a dog that growls when it doesn't recognise the visitors at the door. Chill, buddy, let’s set the headers right so you recognise your guests:
Node.js (Express):
Apache (.htaccess):
Header set Access-Control-Allow-Origin "*"
Nginx (server block):
add_header 'Access-Control-Allow-Origin' '*';
Replace "*"
with the actual domain you trust (like substituting "*" with "squad.com"). This quick trick smoothens development but don't forget to tighten the CORS settings for production.
Tricks for CORS configuration
The Cross-Origin Resource Sharing (CORS) like a strict bouncer that allows only recognised guests (requests from specific origins) on the party(Server) list.
Specify allowed origins
Instead of a party open to all(*
), specify who gets the invite:
PHP:
Apache:
Header set Access-Control-Allow-Origin "http://friend1.com"
Nginx:
add_header 'Access-Control-Allow-Origin' 'http://friend1.com';
ASP.NET (Web.config):
In this way, only friend1.com has the invite to your party(server).
Handling complex CORS scenarios
Suppose you wish to invite not just one friend, but a flexible group of friends or have cookies at your party:
Node.js (Express) with dynamic friends list:
Want to share cookies at the party?
Apache with mod_headers for custom rules:
SetEnvIf Origin "http(s)?://(www\.)?(friend1\.com|friend2\.com)$" ACAO=$0
Header set Access-Control-Allow-Origin %{ACAO}e env=ACAO
Beware the risks
Setting up CORS is like engaging a bouncer. If you loose up too much, you risk your party. So, understand what you are doing and don't expose the users or services to potential threats.
Avoid CORS issues
PhoneGap apps and similar environments will need the server's CORS policy to allow Ajax requests from the app’s domain.
When testing locally, the browser's security rules can be a bit of a buzzkill. Here, tools like Chrome's --disable-web-security
flag can help. Caution: only use this in a trusted development setting and NEVER in production (like using a pass to cut the line at a popular attraction just because you can!).
Tailoring CORS configuration
Think about your CORS configs as designing your house's architecture. Apply CORS headers globally or customize them for specific parts depending upon the needs and demands.
Remove any pre-existing Access-Control-Allow-Origin
header before setting a new one (much like changing your door's lock when moving into a new house).
Lastly, allow only your trusted services. Everything else gets a “Sorry, you’re not on the list!”.
Your comprehension of CORS and related techniques will expedite with time and practice. Additional reading from articles, books, and community discussions also holds the key to in-depth understanding.
Was this article helpful?