7
votes

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
So... I think you can do this with a [piece of middleware](docs.strongloop.com/display/public/LB/Defining+middleware), but I'm having trouble working up an example. I'm going to keep trying though. - Jordan Kasper

1 Answers

6
votes

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