简体   繁体   English

如何在 vue js 中正确获取数据使用 fetch API?

[英]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.我正在尝试使用 GET 方法从后端获取数据,但我总是无法获取数据。 I get the following error: CORS header 'Access-Control-Allow-Origin' missing.我收到以下错误:缺少 CORS header 'Access-Control-Allow-Origin'。 I don't know how it happens because I tried to use POST method to my backend it worked.我不知道它是怎么发生的,因为我尝试使用 POST 方法到我的后端它工作。

Here's a capture of my browser tools这是我的浏览器工具的截图

在此处输入图像描述

When I use fetch to get data it always sends 2 requests, first a OPTIONS then a GET.当我使用fetch获取数据时,它总是发送 2 个请求,首先是 OPTIONS,然后是 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提前致谢

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.这会导致 CORS header 'Access-Control-Allow-Origin' 缺失错误,因为基本上您的客户端无权使用其域访问您的后端。 Add cors headers in your first middleware in the backend.在后端的第一个中间件中添加 cors 标头。 you can set a header of你可以设置一个 header

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.其中https://example.com是客户端应用程序的域。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM