【问题标题】:HTTP request failing in React app due to CORS [duplicate]由于 CORS,React 应用程序中的 HTTP 请求失败 [重复]
【发布时间】:2020-06-30 17:44:33
【问题描述】:

尝试从此 API 获取 JSON 数据,但失败了。关于我需要解决的问题有什么想法吗?

我收到以下错误:

CORS 策略已阻止从源“http://localhost:3000”访问“https://te-e10app01/ERP10/api/v1/Erp.BO.CustomerSvc/Customers”获取... ..

还有错误:

加载资源失败:net::ERR_FAILED

Errors shown here


import React, { Component } from 'react';
import Customers from './components/customers';

class App extends Component {
  render() {

    return (
      <Customers customers={this.state.customers} />
    );

  }

  state = {
    customers: []
  }


  componentDidMount() {
    fetch('https://te-e10app01/ERP10/api/v1/Erp.BO.CustomerSvc/Customers', {
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Authorization": "Basic ##################"
      }
    })
      .then(res => res.json())
      .then((data) => {
        this.setState({ customers: data })
      })
      .catch(console.log)
  }
}

export default App;


【问题讨论】:

  • 您无法在客户端添加 CORS 标头。如果可以,那将毫无意义。您需要在服务器上设置它们,或使用代理。已经有数百篇关于此的帖子,请研究您的特定服务器语言。
  • 好的,非常感谢。那么邮递员是如何工作的呢?我可以使用 Postman 获取这些数据。
  • Postman 不强制执行 CORS。它没有意义:它没有起源。
  • 好的,这是我们使用的 ERP 程序的 API,它们允许 RESTful 服务。请原谅我的无知,我正在学习这一切。我正在尝试使用 REACT 请求数据。
  • 您需要安排服务器 te-e10app01 添加 CORS 响应标头以允许您的前端应用程序(来自不同的域)运行。你能显示端点/ERP10/api/v1/Erp.BO.CustomerSvc/Customers当前产生的响应头吗?

标签: javascript html reactjs request


【解决方案1】:

您需要连接到您的后端,如果您使用的是expressjs,那么它非常容易 通过npm i cors然后const app=reqire('express')(); app.use(cors())安装cors

有 chrome 扩展允许切换 cors 阻塞属性,但这是一个临时解决方案,仅用于测试目的。

【讨论】:

    猜你喜欢
    • 2016-06-18
    • 2021-10-18
    • 1970-01-01
    • 2019-02-21
    • 2016-11-25
    • 1970-01-01
    • 2019-02-04
    • 2017-02-14
    • 2019-11-02
    相关资源
    最近更新 更多