我正在试用新的 Fetch API,但在使用 Cookie 时遇到了问题。具体来说,登录成功后,以后的请求中有一个Cookie头,但Fetch好像忽略了那个头,我用Fetch发出的所有请求都是未经授权的。
是因为Fetch还没有准备好还是Fetch不能和Cookies一起工作?
我用 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
刚刚解决。只有两个 f。蛮力的日子
对我来说,秘诀在于:
我调用 POST /api/auth 并看到 cookie 已成功接收。
然后使用
credentials: 'include'
调用 GET /api/users/ 并得到 401 unauth,因为没有随请求发送 cookie。关键是为第一个
credentials: 'include'
电话设置/api/auth
。
如果您在 2019 年阅读本文,
credentials: "same-origin"
是默认值。
fetch(url).then
在浏览器端以编程方式覆盖
Cookie
标头不会工作.
在
fetch
文档中,注意一些名字是被禁止的。被提及。而Cookie
恰好是禁止的标头名称之一,无法通过编程方式修改。以下面的代码为例:
Cookie: 'xxx=yyy'
将被忽略,如果有的话,浏览器将始终发送document.cookie
的值作为cookie。fetch('https://httpbin.org/cookies', {
headers: {
Cookie: 'xxx=yyy'
}
}).then(response => response.json())
.then(data => console.log(JSON.stringify(data, null, 2)));
附言您可以通过在 chrome 浏览器中打开
https://httpbin.org/cookies/set/foo/bar来创建示例 cookie
foo=bar
。
有关详细信息,请参阅禁止的标头名称。
只需在此处为
.net
webapi2
用户添加正确答案。
如果您正在使用
cors
,因为您的客户端站点是从与您的 webapi
不同的地址提供服务的,那么您还需要在服务器端配置中包含 SupportsCredentials=true
。
// Access-Control-Allow-Origin
// https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api
var cors = new EnableCorsAttribute(Settings.CORSSites,"*", "*");
cors.SupportsCredentials = true;
config.EnableCors(cors);
这对我有用:
import Cookies from 'universal-cookie';
const cookies = new Cookies();
function headers(set_cookie=false) {
let headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
};
if (set_cookie) {
headers['Authorization'] = "Bearer " + cookies.get('remember_user_token');
}
return headers;
}
然后建立你的电话:
export function fetchTests(user_id) {
return function (dispatch) {
let data = {
method: 'POST',
credentials: 'same-origin',
mode: 'same-origin',
body: JSON.stringify({
user_id: user_id
}),
headers: headers(true)
};
return fetch('/api/v1/tests/listing/', data)
.then(response => response.json())
.then(json => dispatch(receiveTests(json)));
};
}
我的问题是我的 cookie 设置在特定的 URL 路径上(例如,
/auth
),但我 fetch
转到了不同的路径。我需要将我的 cookie 的 path
设置为 /
.
我也在用 :
credentials: "same-origin"
它曾经工作,然后它突然不再工作了,在深入挖掘之后我意识到我已经将我的网站 url 更改为
http://192.168.1.100
以在 LAN 中测试它,这就是用于发送请求的 url ,即使我在http://localhost:3000
.
总而言之,确保页面的域与获取 url 的域匹配。