Cookie 未与 Fetch 一起存储

编程入门 行业动态 更新时间:2024-10-25 22:35:46
本文介绍了Cookie 未与 Fetch 一起存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经阅读了我能找到的所有其他主题,但没有一个解决方案有效.我正在使用 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:

auth0/blog/2015/09/28/5-steps-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('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!' }); });

...其中,authenticate 是验证令牌的函数.

...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.我读过关于关闭 httpOnly 和安全以及使用 localhost 的问题.我也尝试过所有主流浏览器,但都没有成功.

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,您应该明确提供 credentials 选项.

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('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 的文章

Credentials:您要用于请求的请求凭据:省略、同源或包含.要为当前域自动发送 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.

更多推荐

Cookie 未与 Fetch 一起存储

本文发布于:2023-10-09 18:04:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1476404.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Cookie   Fetch

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!