将对象编码为 cookie 字符串以进行测试

发布于 2025-01-16 21:56:52 字数 448 浏览 2 评论 0原文

我正在使用 cookie 来传递有关登录用户的会话,并且在服务器上我可以设置并获取它们:

res.cookie("foo", { bar: "baz" })

// later on
console.log(req.cookies.foo) // { bar: "baz" }

现在,我想测试它,并且我需要设置 cookie 标头,但我不知道如何将对象(即 { bar: "baz" })转换为 cookie 计算结果的标头字符串 输入图片此处描述

这里使用的算法是什么?

(我正在使用超级测试,但在我看来这并不重要)

I'm using cookies to pass the session about the logged in user, and on the server I can set and get them fine:

res.cookie("foo", { bar: "baz" })

// later on
console.log(req.cookies.foo) // { bar: "baz" }

Now, I want to test it, and I need to set the cookie header, but I don't know how to convert an object, i.e. { bar: "baz" }, to the header string the cookie evaluates to
enter image description here

What's the algorithm used here?

(I'm using supertest but it shouldn't matter IMO)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ゝ杯具 2025-01-23 21:56:52

默认情况下,express 会对 cookie 进行编码,您需要传递选项以将其保留为字符串。

编码函数 - 用于 cookie 值编码的同步函数。默认为encodeURIComponent。

// Custom encoding
res.cookie("foo", { bar: "baz" }, {encode: String})

您可以在此处查看更多详细信息。

In express by default the cookie is encoded, you need to pass the options to keep it as a string.

encode Function - A synchronous function used for cookie value encoding. Defaults to encodeURIComponent.

// Custom encoding
res.cookie("foo", { bar: "baz" }, {encode: String})

You can check here for more details.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文