When my API, built using expressJS, returns JSON data as a regular response, everything functions smoothly. However, when an error occurs, it returns an error code along with plain text by simply invoking res.sendStatus(401)
.
This poses a challenge on my frontend, where I utilize Angular's ngResource. The resource code looks like this:
svc.authenticateApi = function() {
return $resource(apiEndpoint + 'authenticate', null, {
'save': {
method: 'POST',
transformResponse: function (data, header) {
console.log("transformResponse, header:", header());
console.log("transformResponse, data:", data);
return { data: angular.fromJson(data) };
},
},
});
};
Everything works seamlessly when the API returns normal JSON data. However, when an error status is returned, the data
parameter is not in serialized JSON format; instead, it appears as plain text. This leads to errors such as:
https://i.stack.imgur.com/rLeCP.png
It seems that the transformResponse function attempts to interpret the text "Unauthorized
" as JSON and fails. I could address this problem by ensuring that every error response from the server is sent as JSON, for example by calling `res.status(401).send({error: "Unauthorized"}); however, this workaround feels like a hack, and I would prefer not to manually repeat error messages for each status code.
Is there a more efficient way to handle this issue? I don't mean to sound like I am complaining, but the ngResource documentation is lacking, and I am starting to consider using $http as a better alternative solution.