StrongLoop Loopback: how to configure HTTP response code and header

I am looking for a way to configure the response code and the headers of the StrongLoop LoopBack HTTP code.

I would like to comply with some company business rules regarding REST APIs.

A typical example: for the model described in JSON, have HTTP to respond to a POST request with the Content-Location header of code 201 + (instead of the default response code of 200 without the Content-Location header).

Can this be done with LoopBack?

+5
source share
1 answer

Unfortunately, the way to do this is a bit complicated, because LoopBack doesn’t easily intercept all responses coming out of the API. Instead, you will need to add code for each model to the boot script, which is connected using the afterRemote method:

Inside /server/boot/ add the 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); }; 
+4
source

Source: https://habr.com/ru/post/1215762/


All Articles