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

Unable to change error response code in feathers.js

我使用身份验证服务进行登录验证。因为我想将未授权 (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": {}
}

终于找到解决办法了,我们需要修改钩子错误方法中的响应码。

错误响应代码更改:

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));

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

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