【问题标题】:How can I pass values between koa-router routes如何在 koa-router 路由之间传递值
【发布时间】:2020-02-23 22:07:11
【问题描述】:

我想将认证过程从所有路由转移到一个路由(为此,koa-router 为路由器上的所有方法提供了 all() 中间件)。但是,在此过程中,我解码了一个令牌,我需要对其进行解码才能进一步执行。如何从其他路由访问这个解码的令牌?

const Router = require('koa-router');
const router = new Router({ prefix: '/test' });

router.all('/', async (ctx, next) => {
   //decode
   await next();
})

router.get('/', async ctx=> {
   // Here I need to access decoded, too
});

【问题讨论】:

    标签: koa koa-router


    【解决方案1】:

    Koa Context 对象封装了请求、响应和状态对象,以及更多。此状态对象是推荐的命名空间,您可以在其中在中间件之间传递数据。

    修改提供的示例得到:

    const http = require('http')
    const Koa = require('koa')
    const Router = require('koa-router')
    const app = new Koa()
    const router = new Router({ prefix: '/test' })
    
    router.all('/', async (ctx, next) => {
        // decode token
        const x = 'foo'
        // assign decoded token to ctx.state
        ctx.state.token = x
        await next()
     })
    
     router.get('/', async ctx=> {
        // access ctx.state
        console.log(ctx.state.token)
     })
    
     app.use(router.routes())
    http.createServer(app.callback()).listen(3000)
    
    

    导航到http://localhost:3000/test 并查看已解码的令牌记录到控制台。

    【讨论】:

      猜你喜欢
      • 2020-08-11
      • 2013-09-10
      • 2021-06-29
      • 1970-01-01
      • 1970-01-01
      • 2018-10-09
      • 1970-01-01
      • 2020-04-02
      • 2016-05-02
      相关资源
      最近更新 更多