我正在嘗試新的提取API,但遇到Cookies問題。具體來說,成功登錄後,將來的請求中會包含Cookie標頭,但Fetch似乎忽略該標頭,並且使用Fetch創建的所有請求都是未經授權的。用Cookie提取API
是否因爲Fetch尚未準備好或Fetch無法與Cookie配合使用?
我用Webpack構建我的應用程序。我也在React Native中使用Fetch,它沒有相同的問題。
我正在嘗試新的提取API,但遇到Cookies問題。具體來說,成功登錄後,將來的請求中會包含Cookie標頭,但Fetch似乎忽略該標頭,並且使用Fetch創建的所有請求都是未經授權的。用Cookie提取API
是否因爲Fetch尚未準備好或Fetch無法與Cookie配合使用?
我用Webpack構建我的應用程序。我也在React Native中使用Fetch,它沒有相同的問題。
默認情況下,Fetch不使用cookie。要啓用cookie的,這樣做:
fetch(url, {
credentials: "same-origin"
}).then(...).catch(...);
除了@ Khanetor的回答,對於那些誰與跨域請求工作:credentials: 'include'
樣品JSON讀取請求:
fetch(url, {
method: 'GET',
credentials: 'include'
})
.then((response) => response.json())
.then((json) => {
console.log('Gotcha');
}).catch((err) => {
console.log(err);
});
https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials
同源不再工作,include(請參閱@ Jerry的答案):https://developers.google.com/web/updates/2015/03/introduction-to-fetch – jpic
如何訪問cookie –
@jpic:'include'僅適用於跨源請求,但不適用於同源請求。官方文檔:https://github.com/github/fetch#sending-cookies – HoldOffHunger