StrongLoop Loopback : How to customize HTTP response code and header
Asked Answered
I

1

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 ?

Invitation answered 20/3, 2015 at 14:56 Comment(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.Avunculate
A
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);
};
Avunculate answered 20/3, 2015 at 18:39 Comment(4)
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);Invitation
To do something for all models, seems like you can go this way : docs.strongloop.com/display/public/LB/…Levorotation
ctx.res.status(status).end(); is not a good practice you should call next() and let remoteMethod chain go on.Undershorts
You can add this afterRemote hook in the model js file in common/models/MyModel.js file.Cinchonine

© 2022 - 2024 — McMap. All rights reserved.