本文主要是介绍使用egg.js发送jwt,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
下载jwt 配置jwt
pnpm i egg-jwt
plugin.js
/** @type Egg.EggPlugin */
module.exports = {jwt:{enable:true,package:'egg-jwt'}
};
config.default.js
config.jwt = {secret:"hakurei77" //密钥}
创建中间层
app -> middleware
//检查token
module.exports = (options) => {return async function jwtErr(ctx, next) {const token = ctx.request.header.authorization;let decode = '';if (token) {try {// 解码tokendecode = ctx.app.jwt.verify(token, options.secret);await next();console.log('decode======>',decode);} catch (error) {ctx.status = 401;ctx.body = {message: error.message,};return;}} else {ctx.status = 401;ctx.body = {message: '没有token',};return;}};}
Controller层
async ...() {const { ctx , app } = this;const result = await this.ctx.service.userService....(this.ctx.request.body ,app);ctx.body = result
}
Service层
。。。
const token = app.jwt.sign({UserName: user.UserName,Password: user.Password
},app.config.jwt.secret,{expiresIn:"15s"}) //里面放持续时间
result = {"code": 200,"msg": "成功","data": {"TOKEN": token}
}
路由层
module.exports = app => {const { router, controller,middleware } = app;const jwtErr = middleware.jwtErr(app.config.jwt)router.post("/main" ,jwtErr ,controller.userController.abc)
};
这篇关于使用egg.js发送jwt的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!