Fizzix
Fizzix

Reputation: 24395

How to return an error with Angular http if the data is html?

I'm using Angular's http function to access my remote API service.

At the moment, my API service is offline, and if users try to access it, it still throws a 200 status which is 'ok' with Angular. Therefore, my success callback is always called instead of my error callback. Weird thing is, if I use a REST client, such as POSTman, it has a status of 404?

Here is my function to call my API (using jQuerys $.param() function for URL friendly post parameters):

$http({
  method: 'POST',
  url: "http://mydomain/api/login",
  data: $.param({
     username: "test",
     password: "test"
  }),
  headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(successCallback(response), errorCallback(response));

Here is the response it gives when logged:

{data: "
↵<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN…r at [my ip address] Port 80</address>↵</body></html>↵", status: 200, config: Object, statusText: "OK"}

The response when the API is working is usually something along the lines of:

{
  data: {
    id: 123
  },
  status: 200,
  config: object,
  statusText: 'ok'
}

Sure, theres a few dodgy things that I could do here such as writing a http interceptor to check if data is of type object, yet that's not really the answer I'm looking for here since some of my API calls just return a boolean value.

I also tried changing the 'Content-Type' to 'application/json', yet no luck.

I need my error callback to be used if my API is down. Is there an elegant solution to this?

Upvotes: 0

Views: 591

Answers (1)

8eecf0d2
8eecf0d2

Reputation: 1579

It all sounds a bit hacky, the most appropriate approach I can think of is to send a 404 / 500 from the API endpoints until it comes online.

Otherwise, try to set an Accept header:

{
    'Content-Type': 'application/x-www-form-urlencoded',
    'Accept': 'application/json'
}

Upvotes: 1

Related Questions