StrongLoop Loopback : How to customize HTTP response code and header

北慕城南 提交于 2019-12-08 19:06:50

问题


I'm looking for a way to customize StrongLoop LoopBack HTTP response code and headers.

I would like to conform to some company business rules regarding REST API.

Typical case is, for a model described in JSON, to have HTTP to respond to POST request with a code 201 + header Content-Location (instead of loopback's default response code 200 without Content-Location header).

Is it possible to do that using LoopBack ?


回答1:


Unfortunately the way to do this is a little difficult because LoopBack does not easily have hooks to modify all responses coming out of the API. Instead, you will need to add some code to each model in a boot script which hooks in using the afterRemote method:

Inside /server/boot/ add a file (the name is not important):

module.exports = function(app) {

  function modifyResponse(ctx, model, next) {
    var status = ctx.res.statusCode;
    if (status && status === 200) {
      status = 201;
    }
    ctx.res.set('Content-Location', 'the internet');
    ctx.res.status(status).end();
  }

  app.models.ModelOne.afterRemote('**', modifyResponse);
  app.models.ModelTwo.afterRemote('**', modifyResponse);
};


来源:https://stackoverflow.com/questions/29169519/strongloop-loopback-how-to-customize-http-response-code-and-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!