在环回中以自定义路由访问当前登录的用户ID [英] accessing current logged in user id in custom route in loopback
问题描述
我正在尝试使用context.options在自定义路由中访问当前登录的用户,但发现它为空.尝试像这样在保存之前"访问操作钩子:
I am trying to access the currently logged in user in a custom route using context.options but find it blank. Trying to access in a operational hook 'before save' like this:
'use strict';
module.exports = function (logs) {
logs.observe('before save', async (ctx, next) => {
console.log(ctx.options) //this is empty i.e {}
});
这是我的自定义路由(引导脚本-route.js):
Here is my custom route (boot script - 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一样被填充的自定义路由.在这种情况下,它是空的!
I need the access token and eventually currently logged in user. I believe that the problem is because of the custom route as with rest ctx.options is filled. In this case it is empty!
推荐答案
操作钩子context
接受您提交给它的值以及与模型相关的一些默认值,默认情况下它永远不会具有userId . https://loopback.io/doc/zh/lb3/Operation-hooks.html#operation-hook-context-object
The operation hook context
accepts what values you submit to it, as well as a few defaults related to the model, it would never have the userId by default. https://loopback.io/doc/en/lb3/Operation-hooks.html#operation-hook-context-object
Loopback不会在自定义路由上使用其中间件,因此您需要手动调用它(或在每条路由上使用它).在每个请求的基础上调用中间件的方法如下:
Loopback doesn't use its middleware on custom routes, so you'll need to call it manually (or use it on every route). Here is how you would do it by calling the middleware on a per-request basis
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...
}
`
这篇关于在环回中以自定义路由访问当前登录的用户ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!