使用Express中间件进行每个请求的模块configuration?

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

但是这将是线程安全的吗? 在有多个请求可能同时在运行的环境中,有没有办法使用Express中间件来执行此操作?

换句话说,我在询问示例代码中的Express中间件是设置全局共享variables还是每个请求都由独立线程处理,其中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通常是一个好主意。 这是两个很好的比较: https : //stackoverflow.com/a/14654655/2690845

 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']); });