【问题标题】:loopback use token in headers环回在标头中使用令牌
【发布时间】:2016-09-16 09:15:39
【问题描述】:

我在尝试在模型的 remoteMethods 中恢复我的令牌的用户 ID 时遇到问题。我使用了以下代码:

User.beforeRemote('**', function(ctx, user, next) {
  //...some custom token decoding
  ctx.req.body.user_id = token.user_id;
  console.log('token : ', token);
  next();
});

然后,在我使用的模型中:

User.check = function (user_id, cb) {
  // Do stuff..
}; 


 User.remoteMethod(
    'check',
    {
      http: {path: '/check', verb: 'post'},
      returns: {arg: 'rate', type: 'object'},
      accepts: [
        {
          arg: 'user_id',
          type: 'number',
          required: true,
          description: "id of the user to check",
          http: function getUserid(ctx) {
            console.log('User.check http body : ', ctx.req.body);
            return ctx.req.body.user_id;
          }
        }
      ],
      description: ''

    }
  );

问题是我的 arg 函数“getUserid”在“User.beforeRemote”调用之前被触发。

这是一个错误吗?你知道我该怎么做吗? 我不想使用

arg : {http : {source : 'body'}},

因为我只想在远程方法中使用 user_id arg,而且我必须在大约 20~30 个现有方法中执行此操作

谢谢!

【问题讨论】:

    标签: javascript token loopback


    【解决方案1】:

    我终于找到了一种更简单的方法: 我已经在中间件中添加了我的令牌解码,它工作得很好,有一个经典的 arg 类型号,没有 http 函数:

    //middleware dir :
    module.exports = function (app) {
      "use strict";
    
      return function (req, res, next) {
        //Custom token decoding code ....
        //used req.body to show example with post requests :
        req.body.user_id = parseInt(token.user_id); 
    
        console.log('token : ', token);
        next();
      };
    };
    
    //remote Method declaration, without need to add a beforeRemote method : 
    User.remoteMethod(
        'check',
        {
          http: {path: '/check', verb: 'post'},
          returns: {arg: 'rate', type: 'object'},
          accepts: [
            {
              arg: 'user_id',
              type: 'number',
              required: true,
              description: "id of the user to check"
            }
          ],
          description: ''
        }
      );
    

    【讨论】:

      猜你喜欢
      • 2018-02-28
      • 2016-10-05
      • 2014-09-02
      • 2018-07-08
      • 1970-01-01
      • 2016-11-27
      • 2018-07-05
      • 1970-01-01
      相关资源
      最近更新 更多