我正在尝试使用新的Fetch API但是在使用Cookie时遇到了问题 . 具体来说,在成功登录后,将来的请求中会有一个Cookie标头,但是Fetch似乎忽略了这些标头,而我使用Fetch发出的所有请求都是未经授权的 .
是因为Fetch还没有准备好,或者Fetch不能与Cookies一起使用?
我用Webpack构建我的应用程序 . 我也在React Native中使用Fetch,它没有相同的问题 .
默认情况下,Fetch不使用cookie . 要启用cookie,请执行以下操作:
fetch(url, { credentials: "same-origin" }).then(...).catch(...);
刚刚解决了 . 只有两个f . 残酷的日子
对我来说,秘密在于:
我调用了POST / api / auth,看到cookie已成功收到 .
然后用 credentials: 'include' 调用GET / api / users /并得到401 unauth,因为没有随请求发送cookie .
credentials: 'include'
KEY也是为第一个/ api / auth调用设置 credentials: 'include' .
async function fetchAsync () { let response = await fetch('https://api.github.com/users/pariyathida/repos'); let data = await response.json(); return data; } fetchAsync() .then(data=> data.map(repo => console.log(repo.id))) .catch(reason => console.log(reason.message))
除了@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
4 回答
默认情况下,Fetch不使用cookie . 要启用cookie,请执行以下操作:
刚刚解决了 . 只有两个f . 残酷的日子
对我来说,秘密在于:
我调用了POST / api / auth,看到cookie已成功收到 .
然后用
credentials: 'include'
调用GET / api / users /并得到401 unauth,因为没有随请求发送cookie .KEY也是为第一个/ api / auth调用设置
credentials: 'include'
.除了@Khanetor的回答,对于那些处理跨源请求的人:
credentials: 'include'
示例JSON获取请求:
https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials