javascript - 在 koa.js 中的中间件之间传递值的最佳方式是什么

标签 javascript node.js ejs koa

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

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

最佳答案

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

关于javascript - 在 koa.js 中的中间件之间传递值的最佳方式是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24236192/

相关文章:

javascript - 将查询结果从 Node.js 传递到 html 的变量中

node.js - 创建搜索页面

javascript - 将 html 标签作为 ejs 变量的值传递

javascript - 如何使用 node.js 查询 MySQL?

javascript - 使用 Javascript 创建测验页面

node.js - 运行 “First Electron App”不会显示版本吗?

node.js - 如何使用 Geddy 模型事件

node.js - 如何将ejs转换为jade?

javascript - 转置 JSON 数据

javascript - 如何将某些 javascript 的输出居中?