ReactJS API 数据获取 CORS 错误

时间:2023-04-18
本文介绍了ReactJS API 数据获取 CORS 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

I've been trying to create a react web app for a few days now for my internship and I've encountered a CORS error. I am using the latest version of reactJS, and placing this in the create-react-app, and below is the code for fetching:

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设置.

I'm sorry that I can't post the url for the API due to company rules, however, it is confirmed that there are no CORS setting in the API backend.

但是,我在 mozilla 上运行时遇到以下错误

However, I encounter the following errors when run on 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 上运行,则会出现以下错误

If run on chrome it gives the following error

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

另一件事是,我可以在浏览器中打开网址,没有任何问题.

Another thing is that I am able to open the url in my browsers with no problems or whatsoever.

请帮忙,谢谢!

其他信息

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

The reason I added the CORS setting is because it gives a CORS error, so removing it does not really solve the issue.

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

Next I tried to perform proxy setting, however, it now gives

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

根据互联网,这是因为响应不是 JSON.但是,当我检查 API 时,它给出了这个

According to the internet this is caused becasue the response is not a JSON. However when I checked the API it gives this

api img

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

which means that return type should be a JSON right?

其他信息

检查响应将产生这个

{"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":"美国法院","address_2":"美国","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"}]}

{"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(这不太可能发生),也可以按如下所述解决:

The CORS settings need to be setup in the API to allow access from your React app domain. No CORS settings, no AJAX from different domains. It's simple as that. You can either add CORS settings to your company API (this is unlikely to happen) or you can work around like described below:

CORS 只是客户端浏览器保护用户免受恶意 AJAX 攻击的一种机制.因此,解决此问题的一种方法是将您的 AJAX 请求从您的 React 应用程序代理到它自己的 Web 服务器.正如文森特建议的那样,create-react-app 提供了一种简单的方法来做到这一点:在您的 package.json 文件中,只需简单地夹住 "proxy": "http://your-company-api-domain".有关更多详细信息,请参阅此 链接

The CORS is solely a mechanism of client browser to protect users from malicious AJAX. So one way to work around this is proxying your AJAX request from your React app to its own web server. As Vincent suggests, the create-react-app provides an easy way to do this: in your package.json file, simply chuck "proxy": "http://your-company-api-domain". For more details, please see this link

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

Then in your react app you can using relative URL like this: fetch('/api/endpoints'). Notice that the relative URL has to match with your company API. This will send a request to your server, then the server will forward the request to your company API and return the response back to your app. Since the request is handled in the server-to-server way not browser-to-server so the CORS check won't happen. Therefore, you can get rid of all unnecessary CORS headers in your request.

这篇关于ReactJS API 数据获取 CORS 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:socket.io,“访问控制允许来源"错误 下一篇:Chrome将Origin标头添加到同源请求

相关文章