how to get data use fetch API correctly in vue js?

Tags: , , ,



I’m trying to fetch data from the backend using the GET method, but I always fail to get the data. I get the following error: CORS header ‘Access-Control-Allow-Origin’ missing. I don’t know how it happens because I tried to use POST method to my backend it worked.

Here’s a capture of my browser tools

enter image description here

When I use fetch to get data it always sends 2 requests, first a OPTIONS then a GET. After every request I get this error, then I try to resend request through browser tools, and it works without errors.

Here’s my code:

    fetch("https://sample.com/api-v2/product/group",{
  headers:{
    'Token' : 'asdf213sacxcv'
  }
})
  .then(function (response) {
    if (response.status !== 200) {
      console.log(
        "Looks like there was a problem. Status Code: " + response.status
      );
      return;
    }

    // Examine the text in the response
    response.json().then(function (data) {
      console.log(data);
    });
  })
  .catch(function (err) {
    console.log("Fetch Error :-S", err);
  });

Thanks in advance

Answer

Your backend application runs on a different domain than your client application? That causes the CORS header ‘Access-Control-Allow-Origin’ missing error because basically your client-side is not authorized to access your backend using its domain. Add cors headers in your first middleware in the backend. you can set a header of

Access-Control-Allow-Origin: '*'

to allow any origin to access the backend.

Or setting your specific domain to allow only it to access your backend.

Access-Control-Allow-Origin: 'https://example.com'

Where https://example.com is the domain of your client side application.



Source: stackoverflow