• Home
  • Categories
  • Video Tutorials
    • Angular 5
  • News
  • About us
  • Contact us
  • Login
test
Code4Developers

Code4Developers

Code4Developers
  • Home
  • Categories
  • Video Tutorials
    • Angular 5
  • News
  • About us
  • Contact us
  • Login
  • JavaScript
  • Current
  • Programming

CORS Error And Its Solutions

  • Arif Khoja
  • March 15, 2020
  • 3 minute read
Total
0
Shares
0
0
0

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:

CORS

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.

CORS Gif

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.

cors-works-browser-address-barcors-works-browser-address-bar

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.

CORS-Enabled

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
Arif Khoja

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.

Views: 2,934

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on WhatsApp (Opens in new window) WhatsApp
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on X (Opens in new window) X
  • Click to share on Pinterest (Opens in new window) Pinterest
  • Click to email a link to a friend (Opens in new window) Email
  • Click to print (Opens in new window) Print

Like this:

Like Loading...

Related Posts

Total
0
Shares
Share 0
Tweet 0
Pin it 0

Leave a ReplyCancel reply

Subscribe to Website via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Recent Posts
  • Getting Started with AWS Step Functions: Orchestration Made Simple

    Getting Started with AWS Step Functions: Orchestration Made Simple

    3 months ago
  • React Hooks Guide: Top Tips for Optimizing Performance in Your React Applications

    React Hooks Guide: Top Tips for Optimizing Performance in Your React Applications

    2 years ago
  • Demystifying JavaScript Tree Shaking: Boosting Performance and Reducing Bundle Size

    Demystifying JavaScript Tree Shaking: Boosting Performance and Reducing Bundle Size

    2 years ago
  • Unlocking the Power of React Hooks: A Comprehensive Guide with Examples

    Unlocking the Power of React Hooks: A Comprehensive Guide with Examples

    2 years ago
  • Celebrating a Decade of Phenomenal Growth: Insights and Reflections on 10 Years of Software Engineering

    Celebrating a Decade of Phenomenal Growth: Insights and Reflections on 10 Years of Software Engineering

    2 years ago
  • Angular Custom Elements: Creating Reusable Components with Angular

    Angular Custom Elements: Creating Reusable Components with Angular

    3 years ago
  • Connect Firebase Realtime NoSQL Database with Angular App from Scratch

    Connect Firebase Realtime NoSQL Database with Angular App from Scratch

    5 years ago
  • How to Build an Inclusive Esports Community

    How to Build an Inclusive Esports Community

    5 years ago
  • Best Digital Icebreakers

    Best Digital Icebreakers

    5 years ago
  • Email alerts when a docker container stopped in AWS ECS CLUSTER

    Email alerts when a docker container stopped in AWS ECS CLUSTER

    5 years ago
Subscribe to Website via Email

Enter your email address to subscribe to this website and receive notifications of new posts by email.

Featured Posts
  • javascript 1
    Spread syntax (three dots) in JavaScript
    • March 21, 2018
  • Angular 2
    Angular 6 CRUD – Part 1: Project Setup, Routing, Service
    • May 9, 2018
  • javascript 3
    Local Storage and Session Storage
    • May 22, 2017
  • Angular 4
    Angular 4 Project Structure
    • June 18, 2017
  • AWS 5
    Email alerts when a docker container stopped in AWS ECS CLUSTER
    • July 24, 2020
Code4Developers
Learning is never ending process

Input your search keywords and press Enter.

 

Loading Comments...
 

    %d