捕获 XMLHttpRequest 跨域错误
有没有办法捕获发出请求时由 Access-Control-Allow-Origin
引起的错误?我使用的是 jQuery,并且 .ajaxError()
中设置的处理程序永远不会被调用,因为从未发出请求。
有什么解决方法吗?
Is there any way to catch an error caused by Access-Control-Allow-Origin
when making a request? I'm using jQuery, and the handler set in .ajaxError()
never gets called because the request is never made to begin with.
Is there any workaround?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于 CORS 请求,应触发 XmlHttpRequest 的 onError 处理程序。如果您有权访问原始 XmlHttpRequest 对象,请尝试设置一个事件处理程序,例如:
请注意以下事项:
在 CORS 请求上,浏览器的 console.log 将显示错误消息。但是,该错误消息不适用于您的 JavaScript 代码(我认为这样做是出于安全原因,我之前问过这个问题一次:是否可以捕获 CORS 错误?)。
xhr.status 和 xhr.statusText 未在 onError 处理程序中设置,因此您实际上没有任何关于 CORS 请求失败原因的有用信息。您只知道它失败了。
For CORS requests, the XmlHttpRequest's onError handler should fire. If you have access to the raw XmlHttpRequest object, try setting an event handler like:
Note a few things:
On CORS requests, the browser's console.log will display an error message. However, that error message is not available to your JavaScript code (I think this is done for security reasons, I asked this question once before: Is it possible to trap CORS errors?).
The xhr.status and xhr.statusText aren't set in the onError handler, so you don't really have any useful information as to why the CORS request failed. You only know that it failed.
可以像这样获取错误状态:
来源:https:// /developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
It is possible to get error status like so:
Source: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
为onerror设置处理程序,您将能够捕获跨域异常。我不知道为什么会因异常而触发 onerror 事件,而不是 error 事件,但我刚刚测试了它并且它有效。
Set a handler for onerror and you'll be able to catch the cross-domain exceptions. I don't know why the onerror event is fired for exceptions and not the error event, but I just tested it and it worked.