ReactJS API 数据获取 CORS 错误

2023-04-18前端开发问题
133

本文介绍了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 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

js删除数组中指定元素的5种方法
在JavaScript中,我们有多种方法可以删除数组中的指定元素。以下给出了5种常见的方法并提供了相应的代码示例: 1.使用splice()方法: let array = [0, 1, 2, 3, 4, 5];let index = array.indexOf(2);if (index -1) { array.splice(index, 1);}// array = [0,...
2024-11-22 前端开发问题
182

JavaScript小数运算出现多位的解决办法
在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会...
2024-10-18 前端开发问题
301

JavaScript(js)文件字符串中丢失"\"斜线的解决方法
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转...
2024-10-17 前端开发问题
437

layui中table列表 增加属性 edit="date",不生效怎么办?
如果你想在 layui 的 table 列表中增加 edit=date 属性但不生效,可能是以下问题导致的: 1. 缺少日期组件的初始化 如果想在表格中使用日期组件,需要在页面中引入 layui 的日期组件,并初始化: script type="text/javascript" src="/layui/layui.js"/scrip...
2024-06-11 前端开发问题
455

Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript
Rails/Javascript: How to inject rails variables into (very) simple javascript(Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript)...
2024-04-20 前端开发问题
5

“数组中的每个孩子都应该有一个唯一的 key prop"仅在第一次呈现页面时
quot;Each child in an array should have a unique key propquot; only on first time render of page(“数组中的每个孩子都应该有一个唯一的 key prop仅在第一次呈现页面时)...
2024-04-20 前端开发问题
5