ReactJS API数据获取CORS错误 [英] ReactJS API Data Fetching CORS error

查看:366
本文介绍了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的网址,但是,我们确认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

另一件事是我能够可以在我的浏览器中打开URL,没有任何问题。

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?

其他信息

检查响应将产生此

{状态:200, 总计:1,每页:3,当前页:1,最后一页:1,下一页_url:null,上一页_url:null,从:1,到:3,数据:[{ id:1, slug: america, name: america, address_1: USA Court, address_2: USA, city: USA ,州:美国,邮政编码: 94545,国家/地区代码:美国,电话号码: 10000001,创建者:空,更新者:空,创建者: 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服务器。正如Vincent所建议的那样, create-react-app 提供了一种简便的方法:在您的 package.json 文件中,只需删除 proxy: http://您的公司-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

然后在您的react应用中,您可以使用相对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错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆