简体   繁体   中英

How to check for No 'Access-Control-Allow-Origin' header error

When using XMLHttpRequest in JavaScript, is it possible to distinguish between the following two errors (GET completely failed / No 'Access-Control-Allow-Origin' header)?

错误日志

Obviously, readyState and status of the XMLHttpRequest object don't differ. I tried to use window.onerror to catch all errors but apparently, these two errors do not trigger the callback function.

Your best course of action would be to prevent this error from even occurring in the first place. By making sure the server adds the domain you're trying to access from your script to the Access-Control-Allow-Origin setting you don't have to deal with it client-side.

That said, you should be able to attach a handler to the error event of the XMLHttpRequest object. Using the error message you might be able determine what went wrong; but that is of lesser interest. It doesn't matter to the client what went wrong, only that it isn't going to get it's data, so you can plan accordingly.

var oReq = new XMLHttpRequest();

oReq.addEventListener("error", transferFailed);

oReq.open();

function transferFailed(evt) {
  console.log("An error occurred while transferring the file.");
}

More information: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Asynchronous_request

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM