Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StrongLoop Loopback : How to customize HTTP response code and header

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 ?

like image 577
Nicolas Avatar asked Mar 20 '15 14:03

Nicolas


1 Answers

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);
};
like image 124
Jordan Kasper Avatar answered Oct 13 '22 19:10

Jordan Kasper