安裝 cookies 模塊
npm install cookies -S
代碼如下:
var http = require('http');
var Cookies = require('cookies');
//cookies進(jìn)行簽名(加密)
var keys = ['keyboard cat'];
var server = http.createServer(function (req, res) {
//創(chuàng)建cookie對(duì)象
var cookies = new Cookies(req, res, { keys: keys })
// 獲取cookie,new Cookies時(shí)設(shè)置了簽名谤狡,獲取時(shí)也要進(jìn)行簽名認(rèn)證
var lastVisit = cookies.get('LastVisit', { signed: true });
// 設(shè)置cookie('鍵名','值','有效期')
cookies.set('LastVisit', new Date().getTime(),{ signed: true });
cookies.set('k1', 'v1', { signed: true,maxAge:0 }); //永久有效
cookies.set('k3', 'v3', { signed: true,maxAge:-1 }); //刪除cookie
cookies.set('k2', 'v2',{ signed: true,maxAge:60000*60*24*7 }); //單位毫秒光坝,有效期為7天
if (!lastVisit) {
res.setHeader('Content-Type', 'text/plain;charset=utf8')
res.end('你好帽芽,你這是首次訪問!')
} else {
res.setHeader('Content-Type', 'text/plain;charset=utf8')
res.end('歡迎回來! 上一次訪問時(shí)間為 ' + lastVisit + '.')
}
})
server.listen(3000, function () {
console.log('Visit us at http://127.0.0.1:3000/ !')
})