Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

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

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

question from:https://stackoverflow.com/questions/65897503/how-to-get-data-use-fetch-api-correctly-in-vue-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...