1. 安装jwt插件
npm i express-jwt
2. 在app.js 使用中间件
const expressJwt = require('express-jwt');
//使用中间件验证token合法性
app.use(expressJwt({ secret: 'secret' }).unless({
path: ['/', '/api/user/token', '/api/admin/register', '/api/admin/login',/^\/wx\/.*/,/^\/images\/.*/], //除了这些地址,其他的URL都需要验证
}));
3. 在登录路由 使用
const express = require('express');
const router = express.Router();
// 数据库
let conn = require('../../db/conection');
let formatDate = require('../../utils/formatDate')
// JSON Web Token
const jwt = require("jsonwebtoken");
// 登录
router.post("/login", async (req, res) => {
let { username, password } = req.body;
let selectSql = `SELECT a.*,r.RID,r.RNAME
FROM admin a
left join admin_role ar on a.id=ar.admin_id
LEFT JOIN role r on ar.role_id=r.RID
WHERE a.username = '${username}' AND a.password = '${password}' `;
let results = await conn(selectSql);
// 账号密码错误
if (!results.data.length) {
res.json({
status: false,
msg: "账号或者密码错误!",
});
return false;
}
let { id } = results.data[0];
// 更新登陆时间,登陆次数
selectSql = `UPDATE admin SET login_count = login_count + 1 WHERE id = ${id};`;
let result2 = await conn(selectSql);
if (result2.data.affectedRows > 0) {
// 登录成功
let payload = {
id,
username,
};
// 生成token
let token = jwt.sign(payload, "secret", { expiresIn: "4h" });
res.json({
status: true,
msg: "登录成功!",
data: {
token,
data: results.data[0]
},
});
}
});
- 注意:
let token = jwt.sign(payload, "secret", { expiresIn: "4h" });
payload: 载荷,
secret:对应app.js的app.use(expressJwt({ secret: 'secret' })
expiresIn:过期时长
网友评论