【问题标题】:What's the best way to pass values among middlewares in koa.js在 koa.js 的中间件之间传递值的最佳方式是什么
【发布时间】:2014-08-05 20:03:07
【问题描述】:

我有一个简单的 koa.js 设置,带有 koa-route 和 koa-ejs。

var koa     = require('koa');
var route   = require('koa-route');
var add_ejs = require('koa-ejs');
var app     = koa();

add_ejs(app, {…});

app.use(function *(next){
    console.log( 'to do layout tweak for all requests' );
    yield next;
});

app.use(route.get('/', function *(name) {
  console.log( 'root action' );
  yield this.render('index', {name: 'Hello' });
}));

在这两种方法之间传递值的最佳方式是什么?

【问题讨论】:

    标签: javascript node.js ejs koa


    【解决方案1】:

    context.state 是中间件之间共享数据的底层方式。这是一个挂载在context 上的对象,在所有中间件中都可用。

    你可以这样使用它:

    let counter = 0;
    
    app.use((ctx, next) => {
      ctx.state.requestId = counter++;
      return next();
    });
    
    app.use((ctx, next) => {
      console.log(ctx.state.requestId);
      // => 1, 2, 3, etc
      return next();
    });
    

    source

    koajs readme

    【讨论】:

    • 例如:ctx.state.thingToPassToOtherMiddlware = "Something" 和其他中间件 var thingToPassToOtherMiddlware = ctx.state.thingToPassToOtherMiddlware
    【解决方案2】:

    你可以使用 Koa Context:

    app.use(function *(next) {
      this.foo = 'Foo';
      yield next;
    });
    
    app.use(route.get('/', function *(next) { // 'next' is probably what you want, not 'name'
      yield this.render('index', { name: this.foo });
      yield next; // pass to the next middleware
    }));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-18
      • 1970-01-01
      • 2021-04-28
      • 1970-01-01
      • 2016-04-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多