开发者问题收集

React.js 上的 fetch API 存在问题

2021-02-08
312

当使用其他域来使用 API 并获取数据时,我收到以下错误:

"Access-Control-Allow-Origin"

error_1

在此处输入图像描述

error_2

在此处输入图像描述

我需要您就此问题提供指导...

我的代码:

const url = "https://hornb2b.com/api/products?items_per_page=4&company_id=181";

let headers = new Headers();
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Access-Control-Allow-Credentials', 'true');
headers.append('authority', 'hornb2b.com');
headers.append("Authorization", `Basic ${auth}`);
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9');

fetch(url, {
  method:'GET',
  headers: headers
})
.then(response => response.json())
.then(
  (json) => {
    /*console.log(json);*/
    this.setState({
      isLoaded: true,
      products: json.products
    });
  },
  // Note: it's important to handle errors here
  // instead of a catch() block so that we don't swallow
  // exceptions from actual bugs in components.
  (error) => {
    this.setState({
      isLoaded: true,
      error
    });
  }
)
2个回答

我认为你最好在后端检查 Access-Control-Allow-Origin,而不是从前端,服务器可以修改此选项并允许你获取 api。

Johny Xu
2021-02-08

后端服务器需要允许指示任何其他来源。

例如 Express 服务器 在 main.js 中

import express from "express"
import cors from "cors"
const app = express();
app.use(cors());
Kenneth Leung
2021-02-08