简体   繁体   English

使用Node.js设置HTTP标头Cookie

[英]Set HTTP Header Cookie with Node.js

I am trying to set some header cookies in node.js by using the following method 我正在尝试通过使用以下方法在node.js中设置一些标头cookie

 response.setHeader("Set-Cookie", "username=" + data.name);

the data variable is a json object which contains a number of fields/values, received through a previously sent ajax request. 数据变量是一个json对象,其中包含许多字段/值,这些字段/值是通过先前发送的ajax请求接收的。 The data.name field is definitely populated (a previous console.log(data.name) shows the value correctly). 肯定填充了data.name字段(先前的console.log(data.name)正确显示了该值)。

However, in the browser, once this header has been sent with response.end(), it shows up the following way (in Chrome, while inspecting the response headers in the network tab) 但是,在浏览器中,此标头已通过response.end()发送后,将以以下方式显示(在Chrome中,同时检查“网络”标签中的响应标头)

 Set-Cookie:username=undefined

Does anyone have an idea how to do this properly? 有谁知道如何正确执行此操作?

What I want to accomplish is identifying users throughout a session WITHOUT using any third-party bloat like express.js. 我要完成的工作是在整个会话中识别用户,而无需使用任何第三方膨胀(例如express.js)。 I have already tried using session.js with no success. 我已经尝试使用session.js并没有成功。

Thankful for any ideas. 感谢任何想法。

While I know that you said that you are sure that data.name is defined, your code appears to be so simple, that I am questioning whether it is actually defined. 虽然我知道您说过可以确定已定义data.name ,但您的代码似乎是如此简单,以至于我怀疑它是否实际上已定义。

Rather than logging to console, try setting the the header cookie with some explicit checking: 与其登录控制台,不如通过一些显式检查来设置标头cookie:

response.setHeader(
    "username=" +
    (
        data ?
            data.hasOwnProperty( "name" ) ?
                data.name ?
                    data.name : "name empty"
                : "name undefined"
            : "data undefined"
    )
);

This won't solve your problem, but will help you understand what part of data.name is not working as intended. 这不会解决您的问题,但可以帮助您了解data.name哪个部分无法正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM