What is CORS Error and ways to fix it?

I'm a Software developer with more than 1.5 years of well-rounded experience. My skills include HTML, CSS, C/C++, JavaScript, ReactJS, NodeJS and M ongoDB and Docker. I actively seek out new technologies and stay up-to-date on industry trends and advancements. I enjoy being challenged and engaging with projects that require me to work outside my comfort and knowledge set, as continuing to learn new languages and development techniques are important to me and that also leads to success of any organization. Currently looking for a full time role as a MERN stack developer.
Hello there! As a developer, I'm sure you've seen a lot of mistakes in your time. So, just to make your life a little easier, we'll go over the CORS issue, why it happened, how to fix it, and so on. If you haven't gotten this error yet, consider yourself lucky.
So, what do you think? CORS is really bad!!! Yeah, It is! But have you tried the simpler one? 😛

Let's get started now.
What is CORS?
CORS stands for Cross Origin Resource Sharing. CORS is a mechanism which uses additional HTTP headers to tell the browser whether a specific web app can share resource with another web app. (Here both the web apps should have different origin)
When CORS was not there user can't access the resources like file, some data etc from different origins like punitbatra.co is trying to access google.com/api/ or subdomain like api.punitbatra.co or different ports punitbatra.co:3000 or even different protocols like https can't access from http.
But after CORS became standard browsers do allow these all things. So now to get data from different origins is major issue. Let's see how this works.
If a request does not meet the criteria for a simple request then The browser itself sends a Preflight request (using options method) to the server, which verifies if the call is valid or not. If the call is valid, the server transmits the HTTPS headers, and then the actual call is made, which is how the entire resource sharing process works.
Types of Headers
Access-Control-Allow-Origin : * // Here * shows access to any site. We can give any specific domain also.
Access-Control-Allow-Methods : * // For specifc functions/methods (Get,Post)
Access-Control-Request-Headers : * // Custom headers that will be sent with the request.
How this error looks like? 🐛

In general, we shouldn't call it an error. It's more of a case of expected behaviour. So, let's figure out how to fix this and make it functional 😎...
Ways to fix CORS issue
1. PlugIn 😂
Is it a fix? In short Nope. The access-control-allow-origin plugin essentially turns off the browser’s same-origin policy. For every request, it will add the Access-Control-Allow-Origin: * header to the response. It tricks the browser, and overrides the CORS header that the server has in place with the open wildcard value. This method can help in local environment not in development.
2. Proxy in package.json file
Let's say if your API = http://imdbmovie.com/api/profile/
Then add this part in your package.json file: "proxy": "http://imdbmovie.com/",
and make your request with the next part of the API it must work.
3. Bypass the cross-origin-policy with URL as below
The cors-anywhere server is a proxy that adds CORS headers to a request. A proxy acts as an intermediary between a client and server. In this case, the cors-anywhere proxy server operates in between the frontend web app making the request, and the server that responds with data. Similar to the Allow-control-allow-origin plugin, it adds the more open Access-Control-Allow-Origin: * header to the response.
"https://cors-anywhere.herokuapp.com/{type_your_url_here}"
Say your frontend is trying to make a GET request to https://joke-api-strict-cors.appspot.com/jokes/random
But this api does not have a Access-Control-Allow-Origin value in place that permits the web application domain to access it. So instead, send your GET request to https://cors-anywhere.herokuapp.com/https://joke-api-strict-cors.appspot.com/jokes/random
The proxy server receives the https://joke-api-strict-cors.appspot.com/jokes/random from the url above. Then it makes the request to get that server’s response. And finally, the proxy applies the Access-Control-Allow-Origin: * to that original response.
This solution works in both development and production. One downside of the cors-anywhere proxy is that can often take a while to receive a response. The latency is high enough to make your applications appear a bit sluggish.
4. Set headers manually
resonse_object.header("Access-Control-Allow-Origin", "*");
resonse_object.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
5. Config CORS in the Server-Side
The browser sends a preflight Options requests to the server to check if CORS is enabled on the server. To enable cors on the server side add this to your server code.
app.options("*",function(req,res,next){
res.header("Access-Control-Allow-Origin", req.get("Origin")||"*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
//other headers here
res.status(200).end();
});
6. Config NGINX for proxy_pass
For this, We will have to deploy your code with an nginx server serving as a proxy for both server and client. Configure your nginx server in such a way that the location block handling your particular request will proxy_pass or redirect your request to your actual server.
For example your server is my-server.com and client is my-client.com Configure nginx as follows.
// nginx.conf
upstream server {
server my-server.com;
}
upstream client {
server my-client.com;
}
server {
listen 80;
server_name my-website.com;
access_log /path/to/access/log/access.log;
error_log /path/to/error/log/error.log;
location / {
proxy_pass http://client;
}
location ~ /server/(?<section>.*) {
rewrite ^/server/(.*)$ /$1 break;
proxy_pass http://server;
}
}
Here my-website.com will be the resultant name of the website where the code will be accessible (name of proxy website). Once nginx is configured this way. You will need to modify the requests such that all API calls change from my-server.com/{API-path} to my-website.com/server/{API-path}.

I am sure by using any such way your error will be removed and you can share the resources easily. Anyways, there can be more methods to work with it. But these are some of the popular one's which i have tested too. Here, method 4,5&6 are the best for local and development both. If you know any alternate don't forget to share it in the comments.
Conclusion 💻
As annoying as CORS errors can seem, the same-origin policy is actually a beneficial thing because it stops rogue scripts from accessing data they shouldn't have access to. Fortunately, CORS exists to ensure that we can still perform requests from the browser safely when necessary, allowing developers to access data that enhances user experiences.
Finally, with these fixes, you won't have to worry about seeing that red CORS error in your browser console logs ever again. If you know any alternate to resolve let me know in comments.
If you stayed till here thanks a lot for your time. Don't forget to share the feedback with emojis. In case of any queries/suggestions feel free to reach out to me on Twitter.
Stay tuned for more blogs. 😉

