什么是在koa.js中传递中间件值的最佳方法

bea*_*tak 5 javascript ejs node.js koa

我有一个简单的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' });
}));
Run Code Online (Sandbox Code Playgroud)

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

jbi*_*ick 11

context.state是中间件之间共享数据的低级方式.它是一个安装context在所有中间件上的对象.

资源

koajs自述


rea*_*ess 0

您可以使用 Koa上下文

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
}));
Run Code Online (Sandbox Code Playgroud)