最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What's the best way to pass values among middlewares in koa.js - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked Jun 16, 2014 at 3:14 beatakbeatak 9,59210 gold badges35 silver badges43 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 17

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
}));
发布评论

评论列表(0)

  1. 暂无评论