gpt4 book ai didi

Strongloop:currentContext 在中间件中不可用?

转载 作者:行者123 更新时间:2023-12-03 13:01:09 27 4
gpt4 key购买 nike

我在 middleware.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...。有什么想法吗?

最佳答案

Step 1: In config.json, you need to enable enableHttpContext that is

 "remoting": {
"context": {
"enableHttpContext": true
}

Step 2: Add below code in sever.js before app.start();

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();
});
});

Step 3: add this code in model.js or any js.

var loopback = require('loopback');

var ctx = loopback.getCurrentContext();
var currentUser = ctx && ctx.get('currentUser');
console.log('currentUser.username: ', currentUser);

关于Strongloop:currentContext 在中间件中不可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36006659/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com