在解決fetch跨域請求接口的時候,一般都是讓後臺接口在返回頭裏添加
//允許所有域名的腳本訪問該資源
header("Access-Control-Allow-Origin: *");
確實這樣是可以解決跨域請求的問題,但是如果我們要在請求的時候添加session,那麼這樣設置就會出現問題了。
fetch添加Cookie驗證的方法是設置credentials: 'include'
fetch(url, {
method: 'POST',
body: JSON.stringify(params),
mode: 'cors',
//請求時添加Cookie
credentials: 'include',
headers: new Headers({
'Accept': 'application/json',
"Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
})
})
設置好了之後,信心滿滿的發起請求。卻發現網絡請求報錯了
A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://localhost:3000' is therefore not allowed access
原因是網絡請求需要攜帶Cookie時Access-Control-Allow-Origin是不能設置爲*的,這個時候應該要給Access-Control-Allow-Origin指定域名
這樣就可以達到跨域請求的同時傳遞Cookie的目的了
- 列表項目