Hoffmann Hoffmann - 2 months ago 12x
Node.js Question

Changing status code changes response body in Express

So I have a pretty simple helper function to send errors in my response. I use this function all over my codebase:

exports.error = function (err, res) {
success: false,
errorMsg: err.message,
errors: err.errors == null ? [] : err.errors

I decided to add a status code to it:

exports.error = function (err, res, status) {
success: false,
errorMsg: err.message,
errors: err.errors == null ? [] : err.errors

If the status is 200 I get the body exactly like the object passed to the
method. The problem is that if
is different from 200 (400 or 500 for example) my response body changes to:

config: Object
data: Object
headers: function (d)
status: 500
statusText: "Internal Server Error"

And my original response body (the one with
fields) is inside this new response under the
attribute. I have no idea why this is happening but as far as I know I don't have any other custom error handlers in my application. I don't want this behavior and instead I want only my original response body.

I am using the
package, but I believe that it only affects the requests, not the responses.


The response object that you're getting is Angular's response object (see the documentation):

The response object has these properties:

data{string|Object} – The response body transformed with the transform functions.
status{number} – HTTP status code of the response.
headers{function([headerName])} – Header getter function.
config{Object} – The configuration object that was used to generate the request.
statusText{string} – HTTP status text of the response.

AFAIK, when Angular receives a successful HTTP response (like a 200), it will run any of the default transformations to convert the response to, say, a JS object (from a JSON response).

However, it won't do that when the HTTP response indicates an error. In that case, you will get the above-mentioned response object back.