我正在尝试使用context.options访问自定义路由中的当前登录用户,但发现它为空。在保存之前尝试访问操作挂钩'像这样:
'use strict';
module.exports = function (logs) {
logs.observe('before save', async (ctx, next) => {
console.log(ctx.options) //this is empty i.e {}
});
这是我的自定义路由(启动脚本 - routes.js):
app.get('/logs/dl',(req,res)=>{
logs.create(logs,(err,obj)=>{
if(!err)
{
res.status(200);
res.send(obj);
}
else
{
res.status(500);
res.send('Some problem occurred. Please try again later')
}
});
});
我需要访问令牌并最终登录用户。我认为问题是由于自定义路由,因为其余的ctx.options已填充。在这种情况下它是空的!
答案 0 :(得分:1)
操作挂钩context
接受您提交给它的值,以及与模型相关的一些默认值,默认情况下它永远不会有userId。 https://loopback.io/doc/en/lb3/Operation-hooks.html#operation-hook-context-object
Loopback不会在自定义路由上使用其中间件,因此您需要手动调用它(或在每个路由上使用它)。以下是通过基于每个请求调用中间件来实现的方法
app.start = function() {
var AccessToken = app.registry.getModelByType('AccessToken');
app.get('/logs/dl', (req, res) => {
// loopback.token will get your accessToken from the request
// It takes an options object, and a callback function
loopback.token({model: AccessToken, app: app}) (req, res, () => {
// Once we're here the request's accessToken has been read
const userId = req.accessToken && req.accessToken.userId;
// If you want to give context to a operation hook you use the second parameter
logs.create({color: 'red'}, {contextValue: 'contextValue', userId: userId}, (err, obj) => {
if (!err) {
res.status(200);
res.send(obj);
}
else {
res.status(500);
res.send('Some problem occurred. Please try again later')
}
});
})
});
// the rest of app.start...
}
`