Why ctx.state did not pass to another middleware?

3.4k Views Asked by At

use koa2 ejs koa-router, ejs template how to use another middleware's ctx.state

localhost:3000/admin/usermsg

admin.get('/usermsg', async(ctx) => {    

ctx.state.userMsg = {
    page: Number(ctx.query.page),      
    limit: 4,                            
    pages: 0,                            
    count: count                        
}

var userMsg = ctx.state.userMsg;

ctx.state.users = await new Promise(function(resolve, reject){
    userMsg.pages = Math.ceil(userMsg.count / userMsg.limit);
    userMsg.page = userMsg.page > userMsg.pages ? userMsg.pages : userMsg.page;        
    userMsg.page = userMsg.page < 1 ? 1 : userMsg.page;

    var skip = (userMsg.page - 1) * userMsg.limit;                 

    User.find().limit(userMsg.limit).skip(skip).exec(function(err, doc){
        if(doc){
            resolve(doc);
        }

        if(err){
            reject(err);
        }
    })
})

await ctx.render('admin/usermsg');
})

localhost:3000/damin/category

admin.get('/category', async(ctx) => {
await ctx.render('admin/category');
})

in the category template,can not get ctx.state.userMsg.

how should i get ctx.state.userMsg in category template?

1

There are 1 best solutions below

0
On

Well, assuming userMsg is something you use a lot in your views, you could make a dedicated middleware just to obtain that value.

Middleware work in 'stacks': by calling next(), you can pass control to the next one in the stack (with access to the modified ctx.state). A trivial example:

const setUserMsg = async (ctx, next) => {
  ctx.state.userMsg = await myFuncThatReturnsAPromise()
  await next()
}

router.get('/someroute',
  setUserMsg,
  ctx => { ctx.body = ctx.state.userMsg })

router.get('/someotherroute',
  setUserMsg,
  ctx => { ctx.body = ctx.state.userMsg })

Here, setUserMsg's sole purpose is to extract a value (presumably from the database) and add it to the context.