7

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 ?

Jordan Kasper
  • 13,153
  • 3
  • 36
  • 55
Nicolas
  • 739
  • 7
  • 7
  • 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 Mar 20 '15 at 16:12

1 Answers1

6

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);
};
Jordan Kasper
  • 13,153
  • 3
  • 36
  • 55
  • 1
    Thank you jakerella, it works very well and fit my needs ! I apply it to all my app models like this `for (var model in app.models) app.models[model].afterRemote('**', modifyResponse);` – Nicolas Mar 23 '15 at 17:09
  • 1
    To do something for all models, seems like you can go this way : http://docs.strongloop.com/display/public/LB/Remote+methods#Remotemethods-Formattingremotemethodresponses – neemzy May 02 '15 at 09:25
  • 2
    `ctx.res.status(status).end();` is not a good practice you should call `next()` and let remoteMethod chain go on. – Fran Herrero Jul 06 '16 at 14:59
  • You can add this afterRemote hook in the model js file in `common/models/MyModel.js` file. – asmmahmud Apr 25 '18 at 04:00