angularhttpresponsestatus

Angular Http Error status missing in SecurityClient


I'm using a Http client which is an extended version from Angular 4's Http Client

export class SecurityClient extends Http {
// ...
}

In this client I have methods that attempt calls against an API and I want to catch 401 status to try a refresh token.

I have an implementation like this:

get(url: string, options?: RequestOptionsArgs): Observable<Response> {
        return super.get(url, this._getOptions(options)).catch((initialError: any) => {
            console.log('error: ' + JSON.stringify(initialError));
            if (initialError && initialError.status === 401) {
                return this.authService.doRefreshTokenObservable().flatMap((ok) => {
                    if (ok) {
                        return super.get(url, this._getOptions(options));
                    } else {
                        return Observable.throw('Authentication error');
                    }
                });
            } else {
                return Observable.throw(initialError);
            }
        });
    }

Pretty much similar like angular recommends in its page (https://angular.io/docs/ts/latest/guide/server-communication.html)

But for some reason, the first console.log shows something like:

error: {"_body":{"isTrusted":true},"status":0,"ok":false,"statusText":"","headers":{},"type":3,"url":null}

And I'm unable to get status code at all.

Why is it happening? It's due I'm extending Httpclient and I did something wrong? Even I'm getting this weird status:0, console also shows with red letters:

"No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 401."

(we have the CORS well configured, if token has not expired I retrieve the information successfully)


Solution

  • First, you may want to double check your CORS config on the server. I know, I know, you said you've got it well configured, and I believe you because I've gone through this rigamarole myself. But the CORS response is entirely from the server and shouldn't have anything to do with your AngularJS. I've personally seen Django setups where each response method had it's own CORS configuration, so it's possible that an unauthenticated request is given nothing, including permissions to even make the Cross Origin Request.

    Second, as far as the error code, my first thought is that the server side code that is generating the response should be reviewed. I've never seen Angular return a response code that wasn't straight from the server (which hey, I haven't seen everything). My assumption is that there is perhaps a default status code, or a misconfigured variable that is being returned from the server.

    tl;dr: It seems like both problems, CORS and status: 0 are the fault of something on the server.