【发布时间】:2019-09-29 10:44:00
【问题描述】:
我正在尝试为在我的网络服务器上浏览的用户设置/获取 cookie,我发现了以下 StackOverflow 问题:Get and Set a Single Cookie with Node.js HTTP Server 并且我能够很好地在浏览器上设置 cookie。当我转到 cookie 查看器时,我看到了我想要的设置的 cookie。当我尝试查看 cookie 时出现问题,request.headers.cookie 始终未定义。我将如何在用户浏览器上获取 cookie,最好没有 NPM 模块和纯节点及其自己的模块?
我如何设置 cookie(这很好,当我去查看我的 cookie 时,我可以在浏览器中看到这个 cookie):
response.writeHead(statusCode, {
'Set-Cookie': cookie
})
// statusCode = 200
// cookie = 'token=SOME_TOKEN'
// In the browser I see the exact cookie I set
我如何尝试获取 cookie(始终未定义):
let cookies = request.headers.cookie
// This returns undefined always
// even when I can view the cookie in the
// browser the request is coming from
// Also quick note: I'm currently not
// parsing the cookies out to view them as
// a JSON object because I can not get any
// of the cookies
编辑: 看来我终于找到了错误,它将cookie路径设置为我设置cookie的任何路径,所以我在“/ auth”路由上设置了cookie。我怎样才能使这个 cookie 可以从用户前往的任何路线访问?
【问题讨论】:
-
如果有帮助:我在 ubuntu 上使用 Firefox 浏览器发出浏览器请求并查看 cookie。