0

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?

1 Answer 1

1

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'
}
Sign up to request clarification or add additional context in comments.

4 Comments

Seems to kind of work. Yet it now looks like both the success and error callbacks are being called every time...
@Fizzix, well I knew I was good .. but.. try without the Content-Type header since it should be passed along anyway by angular
Still no luck, both the success and error callbacks are called each time. Weird...
Well, at this point I'd just go back to the original one and check for a string, assuming your api doesn't send strings usually if (typeof data == String) { // is html string } - or wait for someone more knowledgable ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.