Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting status zero instead of 401 in the response

I'm sending a request to a service which requires authentication and since my current state isn't, I'm getting a 401 response. I'm trying to see if I can handle this in my code, at client side and written in Typescript:

this.http.post(url, body, options).catch(e => {
    if (e.status === 401) {
        //Handle 401
    }
    return Observable.throw(e);
});

But the problem is that e.status is zero even though from the network panel I can see that the response's status is actually 401. Is this a problem with Angular or did I do something wrong?

This is the return value for JSON.strigify(e):

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

BTW, I'm using Angular 4.0.0 (core and http).

This is the error I'm getting in the console due to the post request sent above:

(2) POST http://192.168.2.10:8080/test 401 ()
XMLHttpRequest cannot load http://192.168.2.10:8080/test. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.2.10:4200' is therefore not allowed access. The response had HTTP status code 401.

One other mystery is that there are 2 post request errors reported on the console while there's only one sent according to network panel.

like image 527
Mehran Avatar asked Nov 19 '22 17:11

Mehran


1 Answers

I take too long to figure out that problem: you need add OPTIONS in the CORS method configuration in the server side. My final CORS configuration to express is:

const corsOpt = { 
    origin: 'https://www.yourhost.com', // to configure origin url in the server 
    methods: ['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS'], // to work well with web app, OPTIONS is required 
    allowedHeaders: ['Content-Type', 'Authorization'] // allow json and token in the headers 
}; 
like image 170
Ângelo Polotto Avatar answered Dec 05 '22 15:12

Ângelo Polotto