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