使用以下代码执行(故意失败的)跨域请求时:
var request = new XMLHttpRequest();
request.open("GET", 'http://code.jquery.com/jquery-2.1.1.min.js');
request.onerror = function(error) {
alert(error.target.status)
};
request.send()
我将在开发者控制台中收到以下预期错误消息:
XMLHttpRequest 无法加载 http://code.jquery.com/jquery-2.1.1.min.js 请求的资源上不存在“Access-Control-Allow-Origin” header 。因此,不允许访问源“http://localhost”。
但是这个错误消息是来自 XmlHttpRequest 还是来自浏览器?
我想从 XmlHttpRequest 获取该错误消息,但我看不到在哪里。
使用上面的代码,我希望(如 https://stackoverflow.com/a/16931075/343475 中所示)在警报框中看到一条错误消息,但我得到的只是 0
。
最佳答案
But is this error message from the XmlHttpRequest or from the Browser?
XMLHttpRequest 是浏览器的一部分。所以"is"。
如果您的意思是“错误来自服务器还是浏览器”,那么它来自浏览器。服务器无法知道您是否正在发出跨源请求。
With the above code I would expect (as seen in https://stackoverflow.com/a/16931075/343475) to see an error message in the alert box, but all I get is 0.
状态代码将提供有关外源资源的信息(它会告诉您该资源是否存在以及浏览器的用户是否有权访问它),因此它受到同源策略的抑制。
关于javascript - "No ' Access-Control-Allow-Origin' header”错误消息是来自浏览器还是来自 XmlHttpRequest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27526680/