cookie的httpOnly属性
前言
cookie
有一个 httpOnly
属性,可以设置一个 只能在服务端设置的cookie
的键值对,即禁止客户端修改携带 httpOnly
属性的 cookie
键值对。
代码
// app.js
const http = require('http')
const userId = 123456
let resData = {
time: Date.now(),
age: 11,
name: 'xiaoming'
}
// 获取cookie的过期时间
const getCookieExpires = () => {
const d = new Date()
d.setTime(d.getTime() + (24 * 60 * 60 * 1000))
return d.toGMTString()
}
const server = http.createServer((req, res) => {
const method = req.method
// 设置返回格式为json
res.setHeader('Content-Type', 'application/json')
if (method === 'GET') {
res.setHeader('Set-Cookie', `userid=${userId}; path=/; httpOnly; expires=${getCookieExpires()}`)
res.end(JSON.stringify(resData))
}
})
server.listen(8000)
console.log('listening on 8000')
启动一个 node
服务
node app.js