I have this class:
var qs = require('querystring'); class Cookie { constructor(req, res) { this.req = req; this.res = res; } get(name) { if (this.has(name)) { var cookies = qs.parse(this.req.headers.cookie, '; ', '='); return cookies[name]; } return null; } set(name, value) { this.res.setHeader('Set-Cookie', `${name}=${value};`) } delete(name) { if (this.has(name)) { this.set(name, '') } } has(name) { if (typeof this.req.headers.cookie !== 'undefined') { const cookies = qs.parse(this.req.headers.cookie, '; ', '=') return typeof cookies[name] !== 'undefined'; } return false; } }
And then i try this:
const http = require('http'); http.createServer((req, res) => { const cookie = new Cookie(req, res); cookie.set('name', 'Nikita') cookie.set('age', '13') res.setHeader('Content-Type', 'text/plain'); res.write('Now you have cookies') res.end() }).listen(8000)
Then i looked in "Edit This Cookie" and see only last cookie (age=13)
I think this is because there is a variable in the response, where cookies are stored and when I use Set-Cookie, it sets the value for this variable, but how can I get the variables that I added before?
There can be only one Set-Cookie
header, and you are overriding its value each time you call cookie.set
.
The correct approach is to keep a local string variable in the class, and append the new name=value
pair to it each time you call cookie.set
class Cookie
{
var cookieString = ""
// ...
set(name, value)
{
if (cookieString)
{
cookieString += '; '
}
cookieString += `${name}=${value}`
this.res.setHeader('Set-Cookie', cookieString)
}
//...
}
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.