在使用Node.js构建LoopbackJS的项目中,我需要在请求期间存储数据。
所以我使用了域名特性:
// pre-processing middleware
app.use(function (req, res, next) {
// create per request domain instance
var domain = require('domain').create();
// save request and response to domain, to make it accessible everywhere
domain.req = req;
domain.res = res;
domain.run(next);
});稍后在所需模块中:
Model.beforeRemote('**', function(oContext, oModel, next) {
// Save method name for later use
process.domain.remoteContext = { /* Here is an error thrown */
methodName: oContext.method.name
};
...
process.domain.res.send() // example of usage
})但是当我从Safari或IE发出请求时,process.domain有时是没有定义的!从Chrome或Firefox请求按预期工作。有什么建议吗?
错误响应:
{"error":{"name":"TypeError","status":500,"message":"Cannot set property 'remoteContext' of undefined","stack":"TypeError: Cannot set property 'remoteContext' of undefined\n at module.exports (/Users/igormatyushkin/projects/Yash/server/hooks/admin-remote.js:12:34)\n at Function.Model.setup.ModelCtor.beforeRemote.args (/Users/igormatyushkin/projects/Yash/node_modules/loopback/lib/model.js:184:9)\n at execStack (/Users/igormatyushkin/projects/Yash/node_modules/loopback/node_modules/strong-remoting/lib/remote-objects.js:363:13)\n at RemoteObjects.execHooks (/Users/igormatyushkin/projects/Yash/node_modules/loopback/node_modules/strong-remoting/lib/remote-objects.js:372:10)\n at RemoteObjects.invokeMethodInContext (/Users/igormatyushkin/projects/Yash/node_modules/loopback/node_modules/strong-remoting/lib/remote-objects.js:512:8)\n at async.series.results (/Users/igormatyushkin/projects/Yash/node_modules/loopback/node_modules/strong-remoting/node_modules/async/lib/async.js:610:21)\n at _asyncMap (/Users/igormatyushkin/projects/Yash/node_modules/loopback/node_modules/strong-remoting/node_modules/async/lib/async.js:249:17)\n at async.eachSeries.iterate (/Users/igormatyushkin/projects/Yash/node_modules/loopback/node_modules/strong-remoting/node_modules/async/lib/async.js:149:13)\n at async.eachSeries (/Users/igormatyushkin/projects/Yash/node_modules/loopback/node_modules/strong-remoting/node_modules/async/lib/async.js:165:9)\n at _asyncMap (/Users/igormatyushkin/projects/Yash/node_modules/loopback/node_modules/strong-remoting/node_modules/async/lib/async.js:248:13)"}}发布于 2015-03-12 15:59:38
刚刚发现,在创建的时候,说明了将req和res绑定到域,解决了执行堆栈中的未定义域。
app.use(function (req, res, next) {
// create per request domain instance
domain.create().run(function() {
// explicit binding
process.domain.add(req)
process.domain.add(res)
// save request to domain, to make it accessible everywhere
process.domain.req = req;
process.domain.res = res;
next()
});
});不知道为什么会这样,所以我把问题留给其他可能的建议。
发布于 2015-03-12 12:48:02
值得一提的是,域不用于以这种方式处理错误。。相反,域被用来允许整个应用程序的模块安全崩溃(例如,您可能希望在沙箱中运行第三方代码)。在这里没有必要使用域(当然,您可以免费使用)
此外,只有在给定函数从域堆栈中执行时,才会设置process.domain。您没有提供有关model调用站点的信息,因此我只能假设您的模型是从此堆栈外部调用的,这将导致错误。
考虑到您正在链接到beforeRemote,它在执行远程操作之前执行,我将假设这是从域堆栈外部调用的,因此未定义的process.domain是预期的行为。
https://stackoverflow.com/questions/28764830
复制相似问题