In general, to read a status code from a request depends on the library you use. The way you are doing it should by fine. However according to https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/status Browsers also report a status of 0
in case of XMLHttpRequest
errors.
Try listen for the error events on the XMLHttpRequest Object to get more insight in what's going on. That's your specific case, since you are trying to use XMLHttpRequest.
request.addEventListener('error', function (e) {
});
Also you can find lots of different suggestions for status 0
in this SO Question XMLHttpRequest status 0 (responseText is empty)
I also suggest looking into the more modern FETCH API
which is widely supported : https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API .
fetch(myRequest)
.then(response => {
console.log(response.status);
console.log(response.statusText);
return response.json();
})
.then(data => {
/* process your data further */
})
.catch(error => console.error(error));
Example
I added a quick example how to use Fetch API to get Status Code
https://codesandbox.io/s/sad-waterfall-c4k1r
The problem with https://stackoverflow.com/questions/ask/testquestion
specifically is that the request fails du to CORS protection, hence you don't get a status code. You are simply not allowed to request the source. That's a complete other topic.
Problem
Due to reasons like Same Origin Policy, it is not always possible to get a valid status code back.
From Browser
In the Browser ? You can't. Not with simple requests like XMLHttpRequest
or Fetch
due to the issue I mentioned above. The example https://httpstatus.io/ shows that it works, but they are not performing the check within the browser. They are performing the check in their backend/server, somehow simulating a browser with a valid User Agent and showing you the result.
From Server
You can use server side librarys to perform the request for you. I tried the first package I found called got
. Here is an example:
const got = require("got");
const url = "https://stackoverflow.com/";
(async () => {
try {
const response = await got(url, {
throwHttpErrors : false
});
console.log("Status Code : " + response.statusCode);
} catch (error) {
console.error(error);
}
})();
// "Status Code : 200"
const got = require("got");
const url = "https://stackoverflow.com/asdkljasdjklasd";
(async () => {
try {
const response = await got(url, {
throwHttpErrors : false
});
console.log("Status Code : " + response.statusCode);
} catch (error) {
console.error(error);
}
})();
// "Status Code : 404"