I want to set some cookies from the Express server, but I want to do it in a function. I'm not sure about what is internally http ServerResponse, but if I set a header inside the function, that header is not available outside it. E.g, in handler
mySetHeader(res);
// if I check res here there is NO header
function mySetHeader(res) {
res.setHeader('Set-Cookie', serialize('my-cookie', 'my-cookie-value', { path: '/' }));
}
On the other hand if I return res, it works
res = mySetHeader(res);
// if I check res here there IS a header
function mySetHeader(res) {
res.setHeader('Set-Cookie', serialize('my-cookie', 'my-cookie-value', { path: '/' }));
return res;
}
I have looked quickly for some examples where res is passed to a function, but I haven't found much. I wonder if this is an acceptable pattern or if I should do this in another way. Maybe through a middleware or something
The following works for me:
function mySetHeader(res) {
res.setHeader("A", "B");
}
app.use(function(req, res) {
mySetHeader(res);
res.end();
})
The header is set as expected.
Perhaps you need to share more of your code.