I have a simple setup for koa.js with koa-route and 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' });
}));
What's the best way to pass values between those two methods?
context.state
is the low-level way of sharing data between middleware. It's an object mounted on context
that's available in all middleware.
You can use it like so:
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
You can use 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
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With