一、安装依赖
npm install express-session
npm install cookie-parser
二、app.js中注册使用
//注意要放到注册路由之前
const session = require('express-session')
// 使用express-session 来存放数据到session中
app.use(
session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
})
)
三、存储验证码、比对验证码
app.get('/api/v1/login/code', (req, res) => {
// 将验证码存入到 session 中
req.session.verificationCode = '123456'
});
app.post('/api/v1/login',(req,res) => {
const {code} = req.body
// code 获取传递的验证码 ,如果不相等,验证码错误
if(code.toLocaleUpperCase() !== req.session.verificationCode ){
}
})
四、如果出现取值为undefined的情况
import axios from 'axios';
axios.defaults.withCredentials=true; //跨域携带cookie
// 跨域设置
app.all("*", function(req, res, next) {
if (!req.get("Origin")) return next();
// use "*" here to accept any origin
res.set("Access-Control-Allow-Origin",req.headers.origin);
res.set("Access-Control-Allow-Methods", "GET");
res.set("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
res.header('Access-Control-Allow-Credentials', 'true');
// res.set('Access-Control-Allow-Max-Age', 3600);
if ("OPTIONS" === req.method) return res.sendStatus(200);
next();
});