简体   繁体   中英

Node.js - writeHead to set both “Location” and “Set-Cookie”

In node.js(running this in Connect.js), I am able to set ether the Location or Set-Cookie with writehead, but not both at the same time. Currently, the below sets the cooke but the URL does not get redirected to the new location:

function foo(req, res, next) {
    var url = /container-templates/;
    if (url.test(req.url)) {
        console.log(url.test(req.url));
        console.log(req.url);
        res.writeHead(302, ["Location", 'https://staging.dx.host.com' + req.url],
                ["Set-Cookie", "fake-token=5b49adaaf7687fa"]);
        res.end();
    } else { next() }
}

On a side note, I am doing this for the learning experience and do not want to use any pre-written plugins.

Response#writeHead expects the headers to be an Object not a list of array arguments.

The Node HTTP documentation has the following signature defined:

response.writeHead(statusCode, [reasonPhrase], [headers])

If you want to pass in multiple headers your code from above should read:

response.writeHead(302, {
    Location: 'https://staging.dx.host.com' + req.url',
    'Set-Cookie': 'fake-token=5b49adaaf7687fa'
});

The [] on the reasonPhrase means its optional and infers what you've provided to the function based on the types of the arguments.

Also, you don't need to wrap the key part of an object in quotes unless it contains characters that are invalid for variable names (like the - .) And a single ' will do for all strings -- there is no difference in javascript between ' and " .

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