I've modified the code I got from this thread: How to set a cookie age without using a framework in Node.js?
But it only works for the last variable. How can I have both of them working? Here's the code I've tried so far:
res.writeHead(200, {
'Set-Cookie':'test1=' + result[1] + '; expires='+new Date(new Date().getTime()+30 * 60000).toUTCString(),
'Set-Cookie':'test2=' + result[2] + '; expires='+new Date(new Date().getTime()+30 * 60000).toUTCString() // 30 minutes
});
Thank you,
From the node.js docs:
Use an array of strings here to send multiple headers with the same name.
So just do what you're doing but use an array:
res.writeHead(200, {
'Set-Cookie':['test1=' + result[1] + '; expires='+new Date(new Date().getTime()+30 * 60000).toUTCString(),
'test2=' + result[2] + '; expires='+new Date(new Date().getTime()+30 * 60000).toUTCString()] // 30 minutes
});
According to documentation (in my case NodeJS v14):
https://nodejs.org/dist/latest-v14.x/docs/api/all.html#http_request_getrawheadernames
I've tried this:
const cookieTime = 1234567891; //Default Timestamp without ms
const cookieValue1 = "TestVal"; //Cookie Value 1
const cookieValue2 = "AnotherVal"; //Cookie Value 1
const maxAge = 60*60*24; //24h in seconds
const cookieOptions = ";expires="+cookieTime+";domain=.domain.tld;visited=true; Max-Age="+maxAge+"; HttpOnly; Secure";
res.setHeader('Set-Cookie', ['cookie1='+cookieValue1+cookieOptions, 'cookie2='+cookieValue2+cookieOptions]);
This works perfectly fine without any additional modules, despite the obvious ones "http" or "https" for response/request handling in a callback.
Q: Why using res.setHeader() instead of res.writeHead()?
A: In my case, i need to send more data afterwards.
Since my code is ugly here is a snippet of pseudocode:
response = http(s) response from callback
String: Action = 'Set-Cookie'
Array: Cookies = [
String: 'cookieName=cookieValue;cookieOption=cookieOptionValue;....;',
String: 'cookieName=cookieValue;cookieOption=cookieOptionValue;....;',
....,
....
]
response.setHeader(
String: Action,
Array: Cookies
)
If you need further information on available actions or cookie options:
-) available response actions
-) available cookie options
Could be also usefull for this thread: How to set a cookie age without using a framework in Node.js?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With