1.设置 res.cookie()
- res.cookie('name', 'koby', { domain: '.example.com', path: '/admin', secure: true });
- cookie的有效期为900000ms
- res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });
- cookie的有效期为900000ms
- res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true });
- cookie的value为对象
- res.cookie('cart', { items: [1,2,3] });
- res.cookie('cart', { items: [1,2,3] }, { maxAge: 900000 });
- res.cookie('name', 'tobi', { signed: true });
2.获取 req.cookies
3.删除 res.clearCookie("option")
cookie在nodejs中的使用
/**
* Created by prettyRain on 2018/11/26.
*/
//导入express框架
var express = require('express');
//导入cookie插件
var cookie = require('cookie-parser');
var app = express();
app.use(cookie());
/**
* 设置cookie
*/
app.get("/item/:name",function(req,res,next){
var name = req.param('name');
if(name == 'delete'){
//匹配下一个
next();
return;
}
var namearr = req.cookies.cart || [];
namearr.push(name);
//设置cookie
res.cookie('cart',namearr, { items: [1,2,3] });
res.send('');
})
/**
* 获取cookie
*/
app.get("/item",function(req,res){
var namearr = req.cookies.cart || '没有内容';
res.send(namearr);
})
/**
* 删除cookie
*/
app.get("/item/delete",function(req,res){
res.clearCookie("cart");
res.send('');
})
app.listen('3000');
网友评论