使用Fetch不存储Cookie [英] Cookies not being stored with Fetch

查看:214
本文介绍了使用Fetch不存储Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了我可以找到的所有其他主题,没有一个解决方案的工作。我正在使用React + Redux + Express,并尝试按照以下方式将JWT存储在一个cookie中:

I have read every other topic I could find on this and none of the solutions worked. I am using React + Redux + Express and attempting to store a JWT in a cookie as per:

https://auth0.com/blog/2015/09/28 / 5-step-to-add-modern-authentication-to-legacy-apps-using-jwts /

在我的Redux动作中,我发送以下请求:

In my Redux action I am sending the following request:

export function getCookie(token) {
  const config = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + token
    },
    body: JSON.stringify({ token })
  };
  return fetch('http://127.0.0.1:4000/authorize-cookie', config)
   .then((res) => {
     return res.json();
   })
   .then((resJson) => {
     return resJson;
   })
   .catch(err => console.log('Error: ', err));
}

在服务器上我正在回应...

And on the server I am responding with...

app.post('/authorize-cookie', authenticate, (req, res) => {
  res.cookie('id_token', req.body.token, {
    maxAge: 360000
  });
  res.status(200).send({ message: 'Cookie set!' });
});

...认证是验证令牌的功能。

...where authenticate is a function that verifies the token.

我的回应标题一切似乎都很好:

Everything seems fine with my response header:

HTTP/1.1 200 OK
Set-Cookie: id_token=xxx.xxx.xxx; Max-Age=360; Path=/; Expires=Tue, 12 Jan 2016 01:24:03 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 25
ETag: W/"19-UA3htFr0PWczMQBN6T4NpA"
Date: Tue, 12 Jan 2016 01:18:03 GMT
Connection: keep-alive

但是当我查看源标签时,没有找到任何cookie。我已经阅读了关于使用localhost关闭httpOnly和安全问题。我也在每个主要浏览器中尝试过,没有运气。

But when I check the sources tab there's no cookie to be found. I've read about turning off httpOnly and secure and problems with using localhost. I've also tried in every major browser and no luck.

这里发生了什么?

推荐答案

你遇到一个有趣的情况。事实是, fetch 函数的行为是不同的,而不是 XMLHttpRequest 。要使用 fetch 中的Cookie,您应该明确提供凭据选项。

You encountered an interesting case. The thing is that behavior of fetch function is different rather than XMLHttpRequest. To work with cookies in fetch you should explicitly provide credentials option.

fetch('http://127.0.0.1:4000/authorize-cookie', {
    method: 'POST',
    body: JSON.stringify({token: token}),
    credentials: 'same-origin', // <- this is mandatory to deal with cookies
})

根据 MDN上的文章


凭据:要用于请求的请求凭据:省略,同源或包含。要自动发送当前域的Cookie,必须提供此选项。

Credentials: The request credentials you want to use for the request: omit, same-origin, or include. To automatically send cookies for the current domain, this option must be provided.

这篇关于使用Fetch不存储Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆