By the end of this short tutorial, you’ll have a better understanding of:
-
- Why CORS error is occurring?
- What is CORS? and,
Find a few ways to fix CORS error:
-
- Enable CORS
- Make an HTTP Request from a Server
- Use Proxy Server
Let’s say, you will need to make an HTTP request from the client via AJAX to a third-party API or your own API but from a different domain server.
Here is the sample HTTP Request in JavaScript
var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { console.log(xhttp.responseText); } else { console.log("error") } }; xhttp.open("GET", "https://maps.googleapis.com/maps/api/place/details/json?place_id=ChIJryijc9s0K4gRG9aU7SDTXdA&key=[YOURAPIKEY]", true);
And, you will probably get this annoying CORS error:
Recommended → Get User Location with Javascript
The error says…
The browser is blocking the response from Google Places API.
The output response object is coming from the Google Places API and does not have an “appropriate header” to let the browser get data from a different domain.
Oke. The next question you’ll probably ask is…
Why is that?
Well…
By default, browsers will only allow communication between client and server as long as they are in the same domain.
That is called Same Origin Policy and it’s enabled in the browsers by default for security reasons.
When you are typing Google API URL on the address bar, you’re sending a request from a Google server which is the same domain that you’re going to get a response from.
That is the Same Origin Policy and it will work!
But the real question is…
How to make a request via AJAX from the client without getting the CORS error.
Before finding the solution…
Let’s see,
What is CORS?
CORS stands for Cross-Origin Resource Sharing.
It’s a security mechanism that will allow any client to consume data from any domain.
Most of the API service providers will have CORS enabled in their response object as they are meant to be consumed by different domains.
But it’s not in all the cases.
Let’s see how to fix the CORS error.
Enable CORS
Let’s say you have a client-side app and server-side API in two different domains that you manage.
You can simply enable CORS by adding the following header to the response object on the server-side API [NOT IN THE CLIENT] to let the browser know that you have CORS enabled.
In the below example, I have added the code inside middleware in the response object in node.js.
app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "YOUR-DOMAIN.TLD"); // update to match the domain you will make the request from res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); });
And everything will work fine!
But…
What if I am trying to get data from a third-party API like Google Places API that I do not have access to enable CORS?
Making HTTP Requests From The Server
In that case, you can make an HTTP request from your own server rather than the client.
This is because the Same Origin Policy is not applicable when server-to-server communication is happening.
Use Proxy Server
Rather than using your own server, you can use a proxy server from the client making an HTTP Request.
https://cors-anywhere.herokuapp.com/
for more details you can refer this article CORS Anywhere 😀
Conclusion
Now, you have a better understanding of why the CORS error is occurring and how browsers behave.
I also showed you how to fix the CORS error so that when you get the CORS error you stop panicking like I used to do.
I hope it helps!
If you have any questions or if anything is unclear, feel free to reach out to me by simply commenting below.
Happy Coding!
Arif Khoja is a Developer. He is a Javascript Enthusiatic who loves logical programming and has first hand experience in building a cutting edge internet product using Angular. He is also an open source freak and keen about learning and sharing. He writes Javascript both frontend and backend. He loves learning and sharing tech all the time. He also has a hands on experience in SEO and writes articles about latest emerging technologies.