在节点HTTP服务器中获取客户端Cookie

时间:2019-05-12 03:23:57

标签: node.js http cookies

我正在尝试为在我的Web服务器上浏览的用户设置/获取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?

1 个答案:

答案 0 :(得分:1)

好吧,我终于找到了解决方案,我的错误是它正在将cookie的路径自动设置为“ / auth”,所以我只能在所请求的URL包含“ / auth”的情况下访问cookie。 cookie,我将其更改为以下内容:

response.writeHead(statusCode, {
  'Set-Cookie': cookie + '; Path=/'
})

现在我可以访问我的cookie