如何从“访问"环回中访问"req"对象.钩? [英] How to access 'req' object in loopback from "access" hook?

查看:83
本文介绍了如何从“访问"环回中访问"req"对象.钩?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎操作钩子访问"不包含ctx.req对象.

It seems operation hook "access" does not contains ctx.req object.

我想要实现的是会话数据在所有模型中都应该可用.

What i am trying to achieve is that session data should be available in all the models.

在中间件中定义的会话:

Session defined in middleware:

 "session": {
     "express-session": {
         "params": {
         "secret": "mysceret",
         "saveUninitialized": true,
         "resave": true
        }
    }
 }

User.js 中:

req.session.user = userData; 

并以Post模式访问会话:

Post.observe('access', function(ctx, next) {     
   console.log('ctx.req : ' , ctx.req) // undefined
   ctx.query.filter = { tenantId: ctx.req.session.user.tenantId }; 
   // so cannot able to find session data here.   
   next();
}); 

快速会话:"express-session": "^1.15.6"

后备版本:"loopback": "^3.0.0"

我缺少什么或我以错误的方式访问会话? 请一些帮助.

What I am missing or I am access session in a wrong way ? Please some help.

谢谢

推荐答案

如果您已登录,操作挂钩可以从ctx.options中读取accessToken: https://loopback.io/doc/en/lb3/Using-current-context.html#access-the-context-from-operation-hooks

Operation hooks can read the accessToken from ctx.options provided you're logged in: https://loopback.io/doc/en/lb3/Using-current-context.html#access-the-context-from-operation-hooks

Model.observe('access', async ctx => {
  let {options: {accessToken = {}} = {}, ...otherAttributes} = ctx;
  console.log(accessToken);
});

您甚至可以使用链接到"routes:before"部分的中间件来设置accessToken的某些属性,因为中间件具有对reqreq.accessToken的访问权限.

You can even set some properties on the accessToken using a middleware hooked onto the "routes:before" section, since middlewares hace access to req and req.accessToken.

您的中间件可能会说类似以下内容:

Your middleware could say something like:

module.exports = function() {
  return function setSession(req, res, next) {
    let {accessToken} = req;
    accessToken.session = req.session;
    next();
  };
};

however,如果您已经在做:

 req.session.user = userData; 

要将当前用户的值存储到会话中,您可以使用accessToken.user()访问该对象,无论您在何处可以获得对有关令牌的引用.

To store the value of the current user onto the session, you can already access that using accessToken.user() wherever you can get a reference to the token in question.

这篇关于如何从“访问"环回中访问"req"对象.钩?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆