Cookie的使用:
app.js中引入cookie-parser
app.js
~~~
var cookieParser = require('cookie-parser');
app.use(cookieParser());
~~~
使用res对象写入cookie
~~~
router.post('/login', function(req, res, next) {
let username = req.body.username;
let pwd = req.body.pwd;
let u = new userinfo(username, pwd);
//设置cookie
res.cookie("account", u, {maxAge: 60000});
//res.send('{"username":"'+u.username+'","pwd":"'+u.pwd+'"}');
res.json(u);
});
~~~
使用req对象读取cookie
~~~
router.get('/getcookie', function(req, res, next) {
let account = req.cookies["account"];
console.log(account);
//res.send('{"username":"'+u.username+'","pwd":"'+u.pwd+'"}');
res.json(account);
});
~~~
说明:在nodejs中res.cookie可以直接放一个对象,且自动编解码,中文不乱码。
Session的使用:
在app.js中
~~~
var session = require('express-session');
app.use(session({
secret: "sessiontest",
resave: true,
saveUninitialized:true
}));
~~~
需要先安装express-session依赖,否则会报
Cannot find module 'express-session'
在nodejs命令行中运行:
npm install express-session --save
--save代表安装依赖,并且将依赖写入package.json中,运行后发现package.json中多了一行:"express-session": "^1.15.6",
package.json
~~~
{
"name": "hello",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"cookie-parser": "~1.4.3",
"debug": "~2.6.9",
"express": "~4.16.0",
"express-session": "^1.15.6",
"http-errors": "~1.6.2",
"jade": "~1.11.0",
"morgan": "~1.9.0"
}
}
~~~