I am writing a javascript app that makes an HTTP request of a remote server. The user will enter the host name.
I want to offer a diagnostic message if they enter a DNS name that cannot resolve. Here's the current code:
var req, t, url;
url = 'http://definitelydoesntexist0x314159.com';
req = new XMLHttpRequest();
req.open('GET', url, true);
req.onreadystatechange = function() {
if (req.readyState == 4) {
t = req.statusText;
}
};
req.send();
In the onreadystatechange function, the req has status=0, response is "", so there's not much indication of what went wrong. Yet the Console shows "Failed to load resource: net::ERR_NAME_NOT_RESOLVED" so the browser (Chrome) was able to figure out what happened.
How can I get an indication of ERR_NAME_NOT_RESOLVED?
Update: I have come back to this question, using the strategy that any response that isn't 'timeout' means that the name resolved, the host answers, etc.
The answer to my original question seems to be: It appears that the browser itself (Chrome, in this case) detects the failure to resolve and displays it in the Console, but the XMLHttpRequest API isn't rich enough to indicate the cause. So the poor Javascript programmer is stuck with the timeout as a workaround.
I also removed the CORS header, as one of the commenters correctly noted was of no value.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…