{ //debugger; const headers = ne..." />
標籤:

fetch 跨域該怎麼寫?

用的是isomorphic-fetch

前端代碼:

export function fetchMonitoringTarget() {
"use strict";
return dispatch =&> {
//debugger;
const headers = new Headers({
"Content-Type": "application/json",
"Accept": "application/json",
"Origin": "*",
"Access-Control-Allow-Origin": "*"
});
//debugger;
dispatch(requestMonitoringTarget())
return !fetch("http://localhost:3000/monitoring/target", {
method: "GET",
mode: "cors",
cache: "default",
headers
})
.then(resp =&> resp.json())
.then(json =&> dispatch(receiveMonitoringTarget(json)))
.catch(er =&> console.log(er.message))
}
}

錯誤信息:

Fetch API cannot load http://localhost:3000/monitoring/target.
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:6788" is therefore
not allowed access. If an opaque response serves your needs,
set the request"s mode to "no-cors" to fetch the resource with
CORS disabled.


謝邀

標準寫得很詳細了。

Fetch Standard


[分為下面兩種情況]

1. 如果伺服器支持 CORS, 則在客戶端設置相應的 `Access-Control-Allow-Origin` 即可得到數據。

let myHeaders = new Headers({
"Access-Control-Allow-Origin": "*",
"Content-Type": "text/plain"
});
fetch(url, {
method: "GET",
headers: myHeaders,
mode: "cors"
}) .then((res) =&> {
// TODO
})

服務端是否支持可以問下後端同事,如果是自己承擔後端編碼,則可以直接自己設置,比如如果是 PHPer, header 一下響應頭即可。

header("Access-Control-Allow-Origin: *");

2. 如果伺服器不支持 CORS, 則不用使用 Fetch Api 了。

`Fetch Api` 必須後台支持 `CORS`,。咱們可以試下,如果你設置了 `{mode: " cors "}`(一般用於請求API),就會報錯告訴你你請求的伺服器不支持 `CORS`。大概會報下面的錯誤:

Response to preflight request doesn"t pass access control check: No "Access-Control-Allow-Origin" header is present on the requested resource.

如果設置成 `{mode: " no-cors "}` (一般用於請求圖片等靜態資源), 雖然不會報錯,但是結果會 返回被標記了為 `opaque` 的數據,表明你沒有許可權訪問。

這種情況下可以使用 JSONP

題主這種錯誤應該是由於 後端不支持 CORS 造成的。


小伙紙 ,恰好我這幾天也遇到了這個事情,今天被我試出來了,就來跟你分享下的吧。

首先是前端方面,請求而的頭部headers只要配置一個content-type為:application/x-www-form-urlencoded;charset=UTF-8,其他的都不用設置了

export function fetchJSON(url, params) {
// eslint-disable-next-line no-param-reassign
params = {
...params,
headers: {
// "User-Code": code,
// credentials: "include",
// "X-Requested-With": "XMLHttpRequest",
// Connection: "keep-alive",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
...params.headers,
},
}
// eslint-disable-next-line no-param-reassign
url = `${API_PREFIX}${url}${API_SUFFIX}`
return fetch(url, params)
}
function buildParams(obj) {
if (!obj) {
return ""
}
const params = []
// eslint-disable-next-line no-restricted-syntax
for (const key in obj) {
if ({}.hasOwnProperty.call(obj, key)) {
const value = obj[key] === undefined ? "" : obj[key]
params.push(`${key}=${value}`)
}
}
return params.join("")
}
// eslint-disable-next-line arrow-parens
export const fetchJSONByPost = url =&> query =&> {
const params = {
method: "POST",
body: buildParams(query),
}
return fetchJSON(url, params)
}

後端的話,必須設置

Access-Control-Allow-Origin: "*",
Access-Control-Request-Method: "*"

當然Access-Control-Request-Origin後面可以設置為指定的域名,

Access-Control-Request-Method可以設置為post、get、put之類的,這個就看你們自己了,

我這樣的設置之後,比如我的前端工程文件放在10.118.164.206/jcjw這個目錄下面,然後所有的介面統一放在10.118.164.206:8080/jcjw,這樣因為跨埠請求數據,所以會導致請求403,method就變成了options了,我現在改成這樣就請求成功了,這個問題困擾了我好幾天,所以剛才中午解決了我就立馬過來分享了,還望對親有用


去掉headers

fetch("http://localhost:3000/monitoring/target", {
method: "GET",
mode: "cors",
cache: "default"
})

headers會觸發『Preflighted requests』,如果伺服器不支持 prefight 的 options 請求,請求不會成功;

Fetch Standard


肯定會有人問:如何在fetch中使用jsonp?

camsong/fetch-jsonp


Access-Control-Allow-Origin 是server端用的,你前端用它是幾個意思。。。

fetch的配置文件中mode為no-cors的時候可以跨域請求,但是在回調里訪問不到任何response的屬性,真雞肋。。。


推薦閱讀:

移動端自適應疑問?
HTML5與Qt QML僅從做UI的角度比較,哪個更便捷,哪個更強大,哪個(被渲染)性能更高呢?
web開發的迷茫,希望有前輩能告訴一下方向?
原型設計ui設計h5類等生產工具大爆發,設計師們應該何去何從?
HTML 5 遊戲是否有存在的必要?

TAG:HTML5 |