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

In node.js (running this in Connect.js), I can set ether Location or Set-Cookie with a write, but not at the same time. Currently below is installing cooke, but url is not redirecting to 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 the other hand, I'm doing this for learning purposes and don't want to use any pre-written plugins.

+3


source to share


1 answer


Response#writeHead

expects the headers to be an Object, not an array argument list.

Node HTTP documentation has the following signature:

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

      

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



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

      

[]

on reasonPhrase

stands for its optional parameter and passes what you provided to the function based on the types of the arguments.

Also, you don't need to wrap a part of the key

object in quotes if there are no characters in it that are invalid for variable names (e.g -

..) And one '

will do for all strings - in javascript there is no difference between '

and "

.

+3


source







All Articles