使用 Express 中间件进行 per-request 模块配置?

Using Express middleware for per-request module configuration?

假设对我的应用程序的每个请求都包含一个 MAGIC header,并且我想在某处注入该 header 值,而不更新我所有的请求方法。听起来像是中间件的工作,对吧?

但这会是thread-safe吗?在多个请求可能同时运行的世界中,有没有办法使用 Express 中间件来做到这一点?

换句话说,我问的是示例代码中的 Express 中间件是否正在设置全局共享变量,或者每个请求是否由独立线程处理,其中 myconfig 是每个请求的独立副本请求。

示例代码:

var assert = require('assert');
var sleep = require('sleep');

var express = require('express');
var app = express();

var myconfig = {};

app.use(function(req, res, next) {
  myconfig.MAGIC = req.headers['MAGIC'];
  next();
});

app.get('/test', function(req, res) {
  // Pause to make it easy to have overlap.
  sleep(2);
  // If another request comes in while this is sleeping,
  // and changes the value of myconfig.MAGIC, will this
  // assertion fail?
  // Or is the copy of `myconfig` we're referencing here
  // isolated and only updated by this single request?
  assert.equal(myconfig.MAGIC, req.headers['MAGIC']);
});

每个请求都会执行任何中间件函数。当使用中间件设置某些东西的值时,通常将其设置为 app.localsres.locals 是个好主意,具体取决于您希望数据如何持久保存。这是两者的一个很好的比较:

app.use(function(req, res, next) {
  if (req.headers['MAGIC']) {
    app.locals.MAGIC = req.headers['MAGIC'];
  }
  next();
});
...
app.get('/test', function(req, res) {
  assert.equal(app.locals.MAGIC, req.headers['MAGIC']);
});