简体   繁体   English

React.js 上获取 api 的问题

[英]Problems with the fetch api on React.js

When using a different domain to use API and fetch data, I receive the following Error:当使用不同的域来使用 API 并获取数据时,我收到以下错误:

"Access-Control-Allow-Origin" “访问控制允许来源”

error_1错误_1 在此处输入图像描述

error_2错误_2 在此处输入图像描述

I need your guidance regarding this problem...我需要关于这个问题的指导...

Thank You谢谢你

my code:我的代码:

    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
    });
  }
)

I think you'd better examine the Access-Control-Allow-Origin in the back end, not from the front end, the server can modify this option and permit you to fetch api.我认为您最好在后端检查 Access-Control-Allow-Origin,而不是从前端检查,服务器可以修改此选项并允许您获取 api。

The backend server need to allow indicate any other origins.后端服务器需要允许指示任何其他来源。

eg Express server in main.js例如 main.js 中的 Express 服务器

import express from "express"
import cors from "cors"
const app = express();
app.use(cors());

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

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