npm i jsonwebtoken
定义一个密钥
当判断登录成功后加密token后返还给客户机
const jsonwebtoken = require("jsonwebtoken"); if (bcryptjs.compareSync(req.body.password, result[0].password) === true) { const user = result[0] user.password = '' user.tx_pic = '' const secretKey = 'xiaobaiaixuexi^_^' //jsonwebtoken.sign('要加密的字段',密钥,生命时间) const token = jwt.sign(user, secretKey, { expiresIn: '72H' }) //或者写成对象形式(加密单个) const token = jwt.sign({phone:result[0].phone}, secretKey, { expiresIn: '72H' }) res.send({ status: 0, msg: '登陆成功!', token: 'Bearer ' + token }) } }) }
npm i express-jwt
const jwt = require("express-jwt"); //解密密钥 const secretKey = 'xiaobaiaixuexi^_^' app.use(jwt({ secret: secretKey, algorithms: ['HS256'] }).unless({ path: [/\/api\//] }));