主要作用是访问路由接口时,生成身份权限信息
下载依赖
npm i express-jwt
npm i jsonwebtoken
配置管理
config/index.js
module.exports = {app: {port: process.PORT || 3000,//jwt密钥jwtSecret: 'jwtSecret',//token过期时间expiresIn: 60 * 60 * 24,}
}
controller/User.js
const jwt = require('jsonwebtoken')
const { app } = require('../config')
/* 生成token */
const generateToken = (data) => {const created = Math.floor(Date.now() / 1000);const token = jwt.sign(data, app.jwtSecret, {expiresIn: app.expiresIn,});return token;
}/* 用户注册 */
const register = async (req, res, next) => {try {console.log(req.body);const { username, password } = req.body;if (!username || !password) {return res.status(200).json({code: 400,data: [],msg: "用户名或密码不能为空"});}res.status(200).json({code: 200,data: {token: generateToken(req.body)},msg: "注册成功"});} catch (error) {next(error);}
}module.exports = {register
}
routes/user.js(这里分了路由模块化,不懂先看这里expree基本用法-路由模块化-CSDN博客)
const router = require("express").Router()
const { register } = require("../controller/User")
//登录
router.post("/login", register)module.exports = router
效果图