代码之家  ›  专栏  ›  技术社区  ›  lazzy_ms L.D

将会话存储在操作挂钩-环回中

  •  0
  • lazzy_ms L.D  · 技术社区  · 7 年前

    我想存储一些数据 userId 或 accessToken 存储在会话中 after save 或 before save 在环回应用程序中使用操作钩子 express-session .

    我有这个在我的 server/server.js :

    ....
    const session = require('express-session');
    const MongoStore = require('connect-mongo')(session);
    ....
    
    app.use(session({
        name:'session-name',
        secret: 'keyboard cat',
        store: new MongoStore({url: 'mongodb://localhost/test', ttl:1}),
        resave: false,
        saveUninitialized: true
    }));
    

    当我用一些参数定义远程方法时,它实际上传递了参数,而不是 req 反对,所以我不能用快车道。

    如何使用会话存储和获取值?

    编辑: 我找到了一种在远程方法中设置会话的方法,将此添加到model.json模式的远程方法:

    "accepts": [
        {
            "arg": "req",
            "type": "object",
            "http": {
                "source": "req"
            }
        }
    ]
    

    然后,添加 需求 远程方法函数的参数,

    Model.remoteMethod = function (req, callback) {
        req.session.data = { 'foo': 'bar' }
        callback(null)
    };
    

    现在 问题 我想在操作钩子中获取这个会话值吗

    Model.observe('before save', function (ctx, next) {
        //How to get the session here?
    })
    
    0 回复  |  直到 6 年前
        1
  •  0
  •   lazzy_ms L.D    7 年前

    尝试 this now :

    您可以设置ctx值:

    var LoopBackContext = require('loopback-context');
    
        MyModel.myMethod = function(cb) {
          var ctx = LoopBackContext.getCurrentContext();
          // Get the current access token
          var accessToken = ctx && ctx.get('accessToken');
          ctx.set('xx', { x: 'xxxx' } );
    
        }
    

    它是获取ctx值:

     module.exports = function(MyModel) {
          MyModel.observe('access', function(ctx, next) {
            const token = ctx.options && ctx.options.accessToken;
            const userId = token && token.userId;
            const modelName = ctx.Model.modelName;
            const scope = ctx.where ? JSON.stringify(ctx.where) : '<all records>';
            console.log('%s: %s accessed %s:%s', new Date(), user, modelName, scope);
            next();
          });
        };
    

    loopback 上下文存储 userId 和 accesTokan . 在整个web中,您可以使用 ctx 工作就像 session 在里面 回送 .

    推荐文章