我在middlelo.json中以下列方式在Strongloop中配置了我的中间件:
{
"initial:before": {
"loopback#favicon": {}
},
"initial": {
"compression": {},
"cors": {
"params": {
"origin": true,
"credentials": true,
"maxAge": 86400
}
},
"helmet#xssFilter": {},
"helmet#frameguard": {
"params": [
"deny"
]
},
"helmet#hsts": {
"params": {
"maxAge": 0,
"includeSubdomains": true
}
},
"helmet#hidePoweredBy": {},
"helmet#ieNoOpen": {},
"helmet#noSniff": {},
"helmet#noCache": {
"enabled": false
},
"express-jwt": {
"paths": [
"${restApiRoot}"
],
"params": {
"secret": "secret"
}
}
},
"session": {},
"auth": {
"./middleware/token-validation": {
"paths": [
"${restApiRoot}"
]
}
},
"parse": {},
"routes": {
"loopback#rest": {
"paths": [
"${restApiRoot}"
]
}
},
"files": {},
"final": {
"loopback#urlNotFound": {}
},
"final:after": {
"loopback#errorHandler": {}
}
}
此文件由Strongloop生成,除了手动添加“auth”中间件。 在这个中间件(token-validation.js)中,我想像这样访问currentContext:
return function tokenValidation(req, res, next) {
var app = req.app;
var ctx = app.loopback.getCurrentContext();
console.log(ctx);
});
但是,ctx对象始终为null ....有什么想法吗?
答案 0 :(得分:2)
步骤1:在config.json中,您需要启用
的enableHttpContext
"remoting": {
"context": {
"enableHttpContext": true
}
步骤2:在app.start();
之前在sever.js中添加以下代码
app.use(loopback.token()); // this calls getCurrentContext
app.use(loopback.context()); // the context is started here
app.use(function (req, res, next) {
if (!req.accessToken) return next();
// your user model.js
app.models.user.findById(req.accessToken.userId, function(err, user) {
if (err) return next(err);
if (!user) return next(new Error('No user with this access token was found.'));
res.locals.currentUser = user;
var loopbackContext = loopback.getCurrentContext();
console.log('SERVER CTX?' +loopbackContext);
if (loopbackContext) loopbackContext.set('currentUser', user);
next();
});
});
步骤3:在model.js或任何js中添加此代码。
var loopback = require('loopback');
var ctx = loopback.getCurrentContext();
var currentUser = ctx && ctx.get('currentUser');
console.log('currentUser.username: ', currentUser);
答案 1 :(得分:1)
在撰写本文时,建议不要使用getCurrentContext()
。
可能未来的Node版本支持使用当前上下文的可靠基础。
https://strongloop.com/strongblog/context-propagation-in-loopback/