How to return specific http status codes from a remote method to loopback?

I would like to know if there is a way to return a specific HTTP status code from a remote method.

I see that there is a callback function that we can pass to the error object, but how to determine the HTTP status code?

+7
loopbackjs strongloop
source share
4 answers

If you want to use the HTTP status code to report an error, you can pass the error in the remote method callback method:

var error = new Error("New password and confirmation do not match"); error.status = 400; return cb(error); 

Additional information about the error object can be found here: Error object

If you want to simply change the status of the HTTP response without using an error, you can use one of two methods defined by either #danielrvt or #superkhau. To get a reference to the request object specified by #superkhau, you can specify an additional argument in your method registration that will be passed to your remote method. See HTTP input argument mapping

+16
source

When registering a remote method:

 YourModel.remoteMethod('yourMethod', { accepts: [ {arg: 'res', type: 'object', http:{source: 'res'}} ], ... returns: {root: true, type: 'string'}, http: {path: '/:id/data', verb: 'get'} }); 
+2
source

If you just need to change the status of the response, just do:

 ctx.res.status(400); return cb(null); 
0
source

You can return any status code in the same way as in ExpressJS.

 ... res.status(400).send('Bad Request'); ... 

See http://expressjs.com/api.html

-one
source

All Articles