No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API
In need of a quick fix for a CORS error? Make sure, your server sends back the Access-Control-Allow-Origin
header. Here's a simple middleware for your Node.js Express server:
Step-by-step CORS configuration — bringing order into chaos
Now, let's tackle this issue with a secure CORS configuration on a Express.js server. Using middleware cors
package, here is a more detailed configuration:
Remember, Access-Control-Allow-Origin
should match the request origin exactly when credentials are sent.
Running your own CORS proxy server - when you don't call the shots on the server
Sometimes, you don't have the luxury of managing server configurations. In such cases, creating your own CORS proxy server can be a savior.
- Develop a simple proxy server in Node.js and make sure it includes the necessary headers.
- Get that baby up on a cloud service like Heroku.
- In your front-end code, dance with your proxy server's URL instead of the API's.
In 'API_ENDPOINT', sub in the base URL of your target resource. Remember to tackle HTTPS and any needed authentication as well.
Front-end fetch requests - making every request count
When it comes to front-end fetch requests, recall the quote: "It's not about the destination, it's about the journey". Here's how to configure your fetch requests:
Don't gear towards mode: 'no-cors'
unless you don't mind bumping into the js response limitations.
Going beyond CORS and keeping a gamer's spirit
If there's a wall behind the CORS and it seems impenetrable and a proxy server isn't an option, switch the game and go for JSONP. Additionally, if the API demands authentication, you might encode your credentials using base64 and send them in the Authorization header. But beware the ides of the Chrome CORS Plugin — despite its persuasive charm, increasingly, it's seen less as a friend and more as a foe.
Was this article helpful?