問(wèn)題描述
幾天來(lái),我一直在為我的實(shí)習(xí)嘗試創(chuàng)建一個(gè) React Web 應(yīng)用程序,但遇到了 CORS 錯(cuò)誤.我正在使用最新版本的 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))
}
很抱歉,由于公司規(guī)定,我不能發(fā)布API的url,但是,已經(jīng)確認(rèn)API后端沒(méi)有CORS設(shè)置.
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 上運(yùn)行時(shí)遇到以下錯(cuò)誤
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 上運(yùn)行,則會(huì)出現(xiàn)以下錯(cuò)誤
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
另一件事是,我可以在瀏覽器中打開(kāi)網(wǎng)址,沒(méi)有任何問(wèn)題.
Another thing is that I am able to open the url in my browsers with no problems or whatsoever.
請(qǐng)幫忙,謝謝!
其他信息
我添加 CORS 設(shè)置的原因是它給出了 CORS 錯(cuò)誤,因此刪除它并不能真正解決問(wèn)題.
The reason I added the CORS setting is because it gives a CORS error, so removing it does not really solve the issue.
接下來(lái)我嘗試進(jìn)行代理設(shè)置,但是,它現(xiàn)在給出了
Next I tried to perform proxy setting, however, it now gives
Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0
根據(jù)互聯(lián)網(wǎng),這是因?yàn)轫憫?yīng)不是 JSON.但是,當(dāng)我檢查 API 時(shí),它給出了這個(gè)
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
這意味著返回類型應(yīng)該是 JSON 對(duì)嗎?
which means that return type should be a JSON right?
其他信息
檢查響應(yīng)將產(chǎn)生這個(gè)
{"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":"美國(guó)法院","address_2":"美國(guó)","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 中設(shè)置 CORS 設(shè)置以允許從您的 React 應(yīng)用程序域進(jìn)行訪問(wèn).沒(méi)有 CORS 設(shè)置,沒(méi)有來(lái)自不同域的 AJAX.就這么簡(jiǎn)單.您可以將 CORS 設(shè)置添加到您的公司 API(這不太可能發(fā)生),也可以按如下所述解決:
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 只是客戶端瀏覽器保護(hù)用戶免受惡意 AJAX 攻擊的一種機(jī)制.因此,解決此問(wèn)題的一種方法是將您的 AJAX 請(qǐng)求從您的 React 應(yīng)用程序代理到它自己的 Web 服務(wù)器.正如文森特建議的那樣,create-react-app
提供了一種簡(jiǎn)單的方法來(lái)做到這一點(diǎn):在您的 package.json
文件中,只需簡(jiǎn)單地夾住 "proxy": "http://your-company-api-domain"
.有關(guān)更多詳細(xì)信息,請(qǐng)參閱此 鏈接
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
然后在您的反應(yīng)應(yīng)用程序中,您可以使用這樣的相對(duì) URL:fetch('/api/endpoints')
.請(qǐng)注意,相對(duì) URL 必須與您的公司 API 匹配.這將向您的服務(wù)器發(fā)送請(qǐng)求,然后服務(wù)器會(huì)將請(qǐng)求轉(zhuǎn)發(fā)到您的公司 API 并將響應(yīng)返回給您的應(yīng)用程序.由于請(qǐng)求是以服務(wù)器到服務(wù)器的方式而不是瀏覽器到服務(wù)器的方式處理的,因此不會(huì)發(fā)生 CORS 檢查.因此,您可以去掉請(qǐng)求中所有不必要的 CORS 標(biāo)頭.
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.
這篇關(guān)于ReactJS API 數(shù)據(jù)獲取 CORS 錯(cuò)誤的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!