javascript - ReactJS API 数据获取 CORS 错误

标签 javascript reactjs cors

几天来,为了实习,我一直在尝试创建一个 React Web 应用程序,但我遇到了 CORS 错误。我正在使用最新版本的 reactJS,并将其放在 create-react-app 中,下面是获取代码:

componentDidMount() {
  fetch('--------------------------------------------',{
    method: "GET",
    headers: {
      "access-control-allow-origin" : "*",
      "Content-type": "application/json; charset=UTF-8"
    }})
  .then(results => results.json())
  .then(info => {
    const results = info.data.map(x => {
      return {
        id: x.id,
        slug: x.slug,
        name: x.name,
        address_1: x.address_1,
        address_2: x.address_2,
        city: x.city,
        state: x.state,
        postal_code: x.postal_code,
        country_code: x.country_code,
        phone_number: x.phone_number,
      }
    })
    this.setState({warehouses: results, lastPage: info.last_page});
  })
  .then(console.log(this.state.warehouses))
 }

很抱歉,由于公司规定,我无法发布 API 的 url,但已确认 API 后端没有 CORS 设置。

但是在mozilla上运行时遇到如下错误

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ------------------. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ---------------------------------------------. (Reason: CORS request did not succeed).

如果在 chrome 上运行会出现以下错误

Failed to load resource: the server responded with a status of 405 (Method Not Allowed)

Failed to load --------------------------------------------------------: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 405. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Uncaught (in promise) TypeError: Failed to fetch

另一件事是我可以在我的浏览器中毫无问题地打开 url。

请帮忙,谢谢!

附加信息

我添加 CORS 设置的原因是它给出了 CORS 错误,所以删除它并不能真正解决问题。

接下来我尝试执行代理设置,但是,它现在给出

Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0

根据互联网,这是因为响应不是 JSON 造成的。然而,当我检查 API 时,它给出了这个

api img

这意味着返回类型应该是 JSON 对吗?

附加信息

检查响应将产生这个

{"status":200,"total":1,"per_page":3,"current_page":1,"last_page":1,"next_page_url":null,"prev_page_url":null,"from": 1,"to":3,"data":[{"id":1,"slug":"america","name":"america","address_1":"USA Court","address_2":"USA","city":"USA","state":"USA","postal_code":"94545","country_code":"US","phone_number":"10000001","created_by":null,"updated_by":null,"created_at":"2017-11-10 11:30:50+00","updated_at":"2018-06-28 07:27:55+00"}]}

最佳答案

需要在 API 中设置 CORS 设置,以允许从您的 React 应用程序域进行访问。 没有 CORS 设置,没有来自不同域的 AJAX。就这么简单。您可以将 CORS 设置添加到您公司的 API(这不太可能发生),或者您可以像下面描述的那样解决:

CORS 只是客户端浏览器的一种机制,用于保护用户免受恶意 AJAX 攻击。因此,解决此问题的一种方法是将您的 AJAX 请求从 React 应用程序代理到它自己的 Web 服务器。正如 Vincent 所建议的那样,create-react-app 提供了一种简单的方法来执行此操作:在您的 package.json 文件中,只需 chuck "proxy": "http ://你的公司-api-域”。更多详情,请看这个link

然后在您的 React 应用程序中,您可以使用这样的相对 URL:fetch('/api/endpoints')。请注意,相对 URL 必须与您公司的 API 相匹配。这将向您的服务器发送请求,然后服务器会将请求转发给您公司的 API,并将响应返回给您的应用程序。由于请求是以服务器到服务器的方式处理的,而不是浏览器到服务器的方式,因此不会进行 CORS 检查。因此,您可以删除请求中所有不必要的 CORS header 。

关于javascript - ReactJS API 数据获取 CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51128176/

相关文章:

ssl - 通过 HTTPS 的 JSONP

javascript - 第二次点击监听器后 Google 图表卡住

javascript - ie8 中此操作错误的源 HTML 无效

javascript - 鼠标悬停在 d3 矩形上不起作用

reactjs - 为什么 componentWillUnmount 在下一个组件 componentWillMount 之后触发?

javascript - 如何使用 react-chartjs 创建具有动态宽度的折线图?

javascript - 学习者问题 : Functions for every text field. 有没有办法制作一个可以处理多个文本字段的通用函数

javascript - 使用 PrototypeJS 进行跨源资源共享

javascript - 自定义 header 未添加到 Request 对象

javascript - contenteditable <div> 上下文菜单中的新元素