我正在尝试新的Fetch API,但cookie有问题。具体来说,在成功登录后,在未来的请求中有一个Cookie报头,但Fetch似乎忽略了这个报头,并且我所有的请求都是未经授权的。

是因为Fetch还没有准备好,还是Fetch不能与cookie一起工作?

我用Webpack构建我的应用程序。我也在React Native中使用Fetch,它没有同样的问题。


当前回答

如果你是在2019年读这篇文章,凭证:“同源”是默认值。

fetch(url).then

其他回答

刚刚解出来。只是两天的蛮力

对我来说,秘诀如下:

我调用POST /api/auth,看到cookie被成功接收。 然后用凭据调用GET /api/users/: 'include',得到401 unauth,因为请求中没有发送cookie。

KEY是为第一次/api/auth调用设置凭据:'include'。

只是为。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);

除了@Khanetor的回答,对于那些处理跨来源请求的人:凭据:“包括”

示例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

如果你是在2019年读这篇文章,凭证:“同源”是默认值。

fetch(url).then

默认情况下,Fetch不使用cookie。要启用cookie,请执行以下操作:

fetch(url, {
  credentials: "same-origin"
}).then(...).catch(...);