[英]How to manage cookies - with JavaScript or with HTTP Set-Cookie?
[英]Set-Cookie add 2 cookies
我有这门课:
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; } }
然后我试试这个:
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)
然后我查看了“编辑此 Cookie”,只看到最后一个 cookie(年龄 = 13)
我认为这是因为响应中有一个变量,cookie 存储在那里,当我使用 Set-Cookie 时,它设置了这个变量的值,但是我如何获得我之前添加的变量?
只能有一个Set-Cookie
标头,并且每次调用cookie.set
时都会覆盖其值。
正确的做法是在类中保留一个本地字符串变量,并在每次调用cookie.set
时附加新的name=value
对
class Cookie
{
var cookieString = ""
// ...
set(name, value)
{
if (cookieString)
{
cookieString += '; '
}
cookieString += `${name}=${value}`
this.res.setHeader('Set-Cookie', cookieString)
}
//...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.