0

I'm still in trouble with AngularJS 1.5.3.

I'm trying to do some logic with the 401 Unauthorized error in my $http requests.

Here the code.

...
var req = {
  url: 'http://localhost:8080/news',
  method: 'GET'
};
$http(req)
.then(successHandler)
.catch(function(message) {
  console.log(message);
  if(message.status === "401") {
       // logic here
  }
});
...

After running this little piece of code without auth token I got:

Object {data: null, status: -1, config: Object, statusText: ""}

The browser know is 401, and display it in an error before the console.log.

enter image description here

What the heck is happening?

Dinsdale
  • 184
  • 3
  • 12
  • You need to provide additional data. A status of `-1` is usually the result of a timeout or a canceled query. Are you performing a CORS request? What does the request look like? – PerfectPixel Nov 02 '16 at 12:05
  • yep, probably is a CORS problem. I'm using 'slim framework' as backend. The request is simple: an URL and the GET method. The authorization header is left blank by purpose. – Dinsdale Nov 02 '16 at 13:06

1 Answers1

0

I'd recommend taking a look at the documentation of angular's $http and angular's $q (angular promising). Try using .then()-method, it expects two parameters, the first one is the callback in case of a http-success, the second in case of http-error. So you can write something like:

$http.get('http://localhost:8080/api/news').then(
  function(resp) {
    //whatever happens when everything is fine
  }, function(error) {
    console.log(message);
    if(error === "401") {
      // logic here
    }
  }
);

Furthermore $http.get() is a shorthand to your method: 'GET' and promise.catch(errorCallback) is a shorthand for promise.then(null, errorCallback)

Best regards.