Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Example Analysis of ctx return format and Middleware in egg.js Development

Shulou Source: shulou.com Published: 2022-06-01 14:00:49 10月18日 Update

Ctx return format and sample analysis of middleware in egg.js development. Aiming at this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

Ctx return format

App- > extend

Module.exports = {/ / success prompt apiSuccess (data ='', msg = 'ok', code = 200) {this.body = {msg, data}; this.status = code;}, / / failure prompt apiFail (data ='', msg = 'fail', code = 400) {this.body = {msg, data}; this.status = code }, / / generate token getToken (value) {return this.app.jwt.sign (value, this.app.config.jwt.secret);}, / / verify token checkToken (token) {return this.app.jwt.verify (token, this.app.config.jwt.secret);}}; middleware

App- > middleware- > auth.js config.middleware = ['errorHandler','auth']

Module.exports = (option, app) = > {return async (ctx, next) = > {/ / 1. Get the header header token const {token} = ctx.header; if (! token) {ctx.throw (400, 'you do not have permission to access this interface!');} / / 2. According to token decryption, in exchange for user information let user = {}; try {user = ctx.checkToken (token);} catch (error) {let fail = error.name = = 'TokenExpiredError'? 'The token has expired! please reacquire the token': 'Token token is invalid!'; ctx.throw (400, fail);} / / 3. Determine whether the current user logs in to let t = await ctx.service.cache.get ('user_' + user.id); if (! t | | t! = = token) {ctx.throw (400,' Token token is invalid!');} / / 4. Get the current user and verify whether the current user is disabled user = await app.model.User.findByPk (user.id); if (! user | | user.status = = 0) {ctx.throw (400 'user does not exist or has been disabled');} / / 5. Mount user information to the global ctx ctx.authUser = user; await next ();}} this is the answer to the question about the return format of ctx and the sample analysis of middleware in egg.js development. I hope the above content can be of some help to everyone. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Tags: Users middleware formatting analysis tokens questions examples development information more help tips answers validation easy successful easy global content guys Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi vpn MariaDB Docker macOS