如何在node.js中存储请求级variables?
对于在单个请求期间只需要提供的数据,应该在哪里存储? 我正在req和res对象上创build新的属性,所以我不必将数据从函数传递到函数。
req.myNewValue = 'just for this request'
过程对象是一个选项吗? 还是在所有请求中全局共享?
如果你正在谈论通过这样的variables:
http.createServer(function (req, res) { req.myNewValue = 'just for this request'; res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(1337, '127.0.0.1');
那么你正在做的事情是完全正确的。 请求存储请求数据,你可以修改它,如你所愿。 如果你正在使用像Express这样的框架,那么它也应该是好的(请记住,你可以重写一些req
对象的内置属性)。
如果通过“过程对象”来引用全局variablesprocess
,那么绝对不是。 这里的数据是全球性的,不应该被修改。
在Express 4中,最好的做法是在res.locals上存储请求级variables。
包含作用域为请求的响应局部variables的对象,因此仅可用于在请求/响应周期(如果有)期间呈现的视图。 否则,这个属性和app.locals是一样的。
该属性对于公开请求级信息(如请求path名,authentication用户,用户设置等)非常有用。
app.use(function(req, res, next){ res.locals.user = req.user; res.locals.authenticated = ! req.user.anonymous; next(); });
process
对象由所有请求共享,不应该按请求使用。
如果要在asynchronouscallback中保留数据,并且可能存在请求和响应对象不可用的场景。 所以在这种情况下, continuation-local-storage包是有帮助的。
它用于从不容易访问的点访问数据或当前的快递请求/响应。 它使用命名空间的概念。
这是我如何设置这个
安装continuation-local-storage
包
npm install continuation-local-storage --save
创build名称空间
let app = express(); let cls = require('continuation-local-storage'); let namespace = cls.createNamespace('com.domain');
然后是中间件
app.use((req, res, next) => { var namespace = cls.getNamespace('com.domain'); // wrap the events from request and response namespace.bindEmitter(req); namespace.bindEmitter(res); // run following middleware in the scope of the namespace we created namespace.run(function () { // set data on the namespace, makes it available for all continuations namespace.set('data', "any_data"); next(); }); })
现在在任何文件或function,你可以得到这个名字空间,并使用其中保存的数据
//logger.ts var getNamespace = require("continuation-local-storage").getNamespace; let namespace = getNamespace("com.domain"); let data = namespace.get("data"); console.log("data : ", data);