問題描述
幾天來,我一直在為我的實習嘗試創建一個 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 錯誤的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!