4

I have a simple request I make to my service:

 var request = new XMLHttpRequest();
    request.open("OPTIONS", url, true);
    request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
    request.setRequestHeader('Accept', 'application/json');

    request.onreadystatechange = function () {
        if (request.readyState != 4) {
            return;
        }

        var authType = request.getResponseHeader("WWW-Authenticate");

        makeRequest(...);
    };

    request.send();
}

So what I'm trying to achieve is make a call to my endpoint to see what's the authorisation type (basic or bearer) and then when I get the auth type I will make the actual request with the proper credentials.

If I make the request manually I get the 401 unauthorised which is normal but I also get the WWW-Authenticate: Basic ... in my headers. However if I do this javascript call it will just fail with 401:unauthorised but I don't get this failed response in my callback so the authType will be undefined.

I haven't used javascript before so the question is how can I get the response in the callback even if the request failed with unAuthorised ?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Fofole
  • 3,398
  • 8
  • 38
  • 59
  • 1
    [`XMLHttpRequest.getResponseHeader()`](https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#the-getresponseheader()-method): Step 2: "If the error flag is set, return null." – Andreas Oct 26 '15 at 13:06
  • That is indeed why no response is set. For now I used a workaround and will keep the question opened until I/someone will find a general solution. – Fofole Oct 27 '15 at 07:48
  • A "general solution" would be to change the specification, which isn't very likely :) – Andreas Oct 27 '15 at 07:53

1 Answers1

0

XMLHttpRequest has an onerror callback that you can use:

var request = new XMLHttpRequest();
...
request.onerror = function(){
    if (this.status == 401) {
    } 
} 
...
request.send();
Lucas Rodrigues
  • 1,234
  • 2
  • 11
  • 22