javascript - 有没有办法从 ajax 预检请求中获取调试信息?

标签 javascript jquery ajax cors

我有一些使用 ajax 发出 ajax 请求的 javascript。此请求的预检 OPTIONS 调用失败。我想向用户显示一些有关调用及其状态代码的调试信息 - 如何从错误回调中的 jqXhr 对象获取此信息?

$.ajax
  url: url
  headers: headers
  ...
  error: (jqXhr, status) =>
    # how can I get info about OPTIONS call here?

最佳答案

目前,这根本不可能。

当飞行前请求因任何原因失败时,CORS 严重缺乏错误信息,两者都在 spec 中,以及在浏览器实现中。相关摘录自HTML5 Rocks :

If there is an error in the CORS request, the browser will fire the client's onerror event handler. It will also print the following error to the console log:

XMLHttpRequest cannot load http://api.alice.com. Origin http://api.bob.com is not allowed by Access-Control-Allow-Origin.

浏览器不会向您提供有关错误发生原因的大量详细信息,它只会告诉您出了点问题。

... 它接着说(在 known issues) 下:

No error information provided to onerror handler - When the onerror handler is fired, the status code is 0, and there is no statusText. This may be by design, but it can be confusing when trying to debug why CORS requests are failing.

事实上,您会发现 jqXHR statusText 属性将为空,status 代码将为 0,并且 getAllResponseHeaders() 将返回一个空字符串。

需要说明的是:这是从底层 XMLHttpRequest 对象中获取数据的问题。这并不是说 jQuery 正在屏蔽信息或以其他方式不提供信息;在这种情况下,(目前)根本不可能从 XmlHttpRequest 对象中获取错误数据。

关于javascript - 有没有办法从 ajax 预检请求中获取调试信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24889382/

相关文章:

javascript - Firefox 不执行动态加载的 JavaScript 文件

javascript - 元素的 svg.js 动画旋转给出了意想不到的结果(可见 "jiggling")

javascript - 如果有多个复选框切换事件

javascript - 在 Javascript 中刷新 $(document).ready

php - 如何在php中捕获json返回值

javascript - fetch(或 AJAX Get)返回 html,但 Postman 从 feedburner 返回 xml

javascript - 我正在尝试使用 NodeJS 从 JSON 数据中提取某些值

javascript - angular-bootstrap-slider 默认值/双向绑定(bind)

javascript - fancybox ajax 发布到 iframe

javascript - Jquery getJSON 填充选择菜单问题