First,install cookie-parser middleware
npm install cookie-parser
and then
var cookieParser = require("cookie-parser");
app.use(cookieParser());
next
app.get("/setcookie",function(req,res){
res.cookie('name1','setcookie')
})
app.get("/getcookie",function(req,res){
console.log(req.cookies);
})
you can set siged(签名)
var cookieParams ={
maxAge:3600000,
signed:true
};
app.use(cookieParser("djhskajhdskjahdjsa"));
app.get("/setcookie",function(req,res){
res.cookie('name1','setcookie',cookieParams);
})
use encrypted
npm install cookie-encrypter
var cookieEncrypter = require("cookie-encrypter");
const secretKey ="adsadsjadssdaadsdasajdksjadsadsa" //must be 32bit (with aes256)
app.use(cookieParser(secretKey));
app.use(cookieEncrypter(secretKey));
app.get("/setcookie",function(req,res){
res.cookie('name1','setcookie',cookieParams);
res.cookie('age1',{mydata:'is encrypted'},cookieParams)
res.cookie('plaincookie','mytest',cookieParams);
res.cookie('plaincookie2',{mydata:'is encrypted'},cookieParams)
res.json({code:0});
})
app.get("/getcookie",function(req,res){
// var name=req.cookie.name;
// var age = req.cookie.age;
// res.json({"name":name,"age":age});
console.log(req.cookies);
console.log(req.signedCookies)
res.json({code:0})
})
you can get value
console.log(req.cookies);
console.log(signedCookies);
clear cookie
app.get("/clearcookie",function(req,res){
res.clearCookie("age1");
res.json({code:0});
})