无法更改feathers.js中的错误响应代码

时间:2017-11-07 05:18:15

标签: javascript node.js response middleware feathersjs

我使用身份验证服务进行登录验证。因为我希望Unauthorized(401)响应代码为200,并且消息应该相同。

我的身份验证服务是

app.service('authentication').hooks({
    before: {
      create: [
        authentication.hooks.authenticate(config.strategies),
        function (hook) {
         hook.params.payload = {
            userId: hook.params.user.userId,
            accountId: hook.params.user.accountId
          };
          return Promise.resolve(hook);
        }
      ],
      remove: [
        authentication.hooks.authenticate('jwt')
      ]
    },
    after: {
      create: [ function(hook,next){
          hook.result.statusCode = 201; 
          hook.result.authentication = "user login successful";
          next();
        }
      ]
    }
  });

我的中间件代码是

app.use(function(err, req, res, next) {
  res.status(err.status || 200);

  res.format({
    'text/html': function(){
      // Probably render a nice error page here
      return res.send(err);
    },

    'application/json': function(){
      res.json(err);
    },

    'text/plain': function(){
      res.send(err.message);
    }
  });
});

我的回复信息是

{
    "name": "NotAuthenticated",
    "message": "Invalid login",
    "code": 401,
    "className": "not-authenticated",
    "data": {
        "message": "Invalid login"
    },
    "errors": {}
}

但我想要

{
    "name": "NotAuthenticated",
    "message": "Invalid login",
    "code": 200,
    "className": "not-authenticated",
    "data": {
        "message": "Invalid login"
    },
    "errors": {}
}

2 个答案:

答案 0 :(得分:0)

最后我找到了解决方案。我们需要在钩子错误方法中更改响应代码。

错误响应代码更改

app.service('authentication').hooks({
    before: {
      create: [
        authentication.hooks.authenticate(config.strategies),
        function (hook) {
         hook.params.payload = {
            userId: hook.params.user.userId,
            accountId: hook.params.user.accountId
          };
          return Promise.resolve(hook);
        }
      ],
      remove: [
        authentication.hooks.authenticate('jwt')
      ]
    },
    after: {
      create: [ function(hook,next){
          hook.result.code = 200; 
          hook.result.authentication = "user login successful";
          next();
        }
      ]
    },
    error: {
      create: [function(hook, next){
        hook.error.code = 200;
        next();
      }]
    }
  });
结果响应代码更改

function restFormatter(req, res) {
  res.format({
    'application/json': function() {
      const data = res.data;
      res.status(data.__status || 200);
      res.json(data);
    }
  });
}

app.configure(rest(restFormatter));

答案 1 :(得分:0)

另一种选择是通过在hook.result处理程序中设置error来吞下错误,该处理程序将自动返回成功的HTTP代码:

app.service('authentication').hooks({
  error: {
    create: [ function(hook, next){
      hook.result = { authentication = "user login successful" };
    } ]
  }
});