在 Loopback 中更改响应主体 404

Change response body 404 in Loppback

我是环回的新手。当找不到模型记录时,我正在尝试覆盖响应正文。

这是资源管理器的默认响应正文:

{
  "error": {
    "statusCode": 404,
    "name": "Error",
    "message": "could not find a model with id 666",
    "code": "MODEL_NOT_FOUND",
    "stack": "..."
  }
}

我的预期结果:

{
    "status": 404,
    "message": "could not find a model with id 666"
}

https://loopback.io/doc/en/lb3/Defining-middleware.html#middleware-phases

final - Deal with errors and requests for unknown URLs.

  app.middleware('final', function(err, req, res, next) {
    if (err && err.code === 'MODEL_NOT_FOUND') {
      res.statusCode = 404;
      res.json({status: 404, message: err.message});
    }else {
      next();
    }
  });

使用 boot 目录中的文件、middleware.json 指向的文件或 server.js.

中的文件注册