假设对我的应用程序的每个请求都包含一个MAGIC
标头,并且我想将该标头值注入某个位置,而不更新所有请求方法。听起来这是中间件的工作,对吧?
但这将是线程安全的吗?在一个可能同时发送多个请求的环境中,有没有办法使用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.locals
或res.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']);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句