检查失败的HTTP请求

时间:2018-09-28 17:01:29

标签: javascript html http

有没有办法检查JavaScript中失败的HTTP请求?例如

<img src="foo.com">

将失败,并显示一条消息(在Chrome开发工具中):

Failed to load resource: the server responded with a status of 404

我想在javascript中捕获相同的HTTP错误。

1 个答案:

答案 0 :(得分:2)

一旦出现错误,您将不得不记录该错误。在此处到达timeout时,它将引发一个错误事件。

window.addEventListener('error', function(e) {
    console.log(e);
}, true);
<img src="foo.com">

输出:

{
  "isTrusted": true,
  "NONE": 0,
  "CAPTURING_PHASE": 1,
  "AT_TARGET": 2,
  "BUBBLING_PHASE": 3,
  "type": "error",
  "target": <img src="foo.com"></img>,
  "currentTarget": {
    /**id:2**/
    "postMessage": function () { [native code] },
...
相关问题