简体   繁体   中英

Set HTTP Header Cookie with Node.js

I am trying to set some header cookies in node.js by using the following method

 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. The data.name field is definitely populated (a previous console.log(data.name) shows the value correctly).

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)

 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. I have already tried using session.js with no success.

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.

Rather than logging to console, try setting the the header cookie with some explicit checking:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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