11

koa-route と koa-ejs を使用した koa.js の簡単なセットアップがあります。

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' });
}));

これら 2 つのメソッド間で値を渡す最良の方法は何ですか?

4

2 に答える 2

16

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();
});

ソース

koajs readme

于 2015-03-01T20:54:23.610 に答える
1

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
}));
于 2014-06-16T19:08:01.537 に答える