javascript - 如何使用 XMLHttpRequest() 和 Javascript 处理 POST 请求错误

标签 javascript http post error-handling request

我正在尝试处理 HTTP 请求引发的错误,但无法正确拦截该事件。

POST http://localhost:8080/path/to/endpoint 500 (Internal Server Error)

我在页面上有一个放置区域,用于接收文件并在服务器上解析它。当文件格式正确时,它可以正常工作,但我正在尝试处理由格式不正确的文档引起的错误。

根据 Mozilla 文档,XMLHttpRequest 有一个 onerror 函数,但当我尝试按如下方式使用它时,它会被绕过:

_postRequest() {
  let files = this.files[0];
  let data = new FormData();
  let request = new XMLHttpRequest();

  // File selected by the user - in case of multiple files append each of them
  data.append('file', this.files[0]);

  // AJAX request finished
  request.addEventListener('load', (e) => {
    // Send response to DOM
    this.dispatchEvent(new CustomEvent('return-validated-items', {
      bubbles: true, composed: true,
      detail: request.response
    }));
  });

  // If server is sending a JSON response then set JSON response type
  request.responseType = 'json';

  // Send POST request to the server side script
  request.open('post', 'http://localhost:8080/path/to/endpoint');
  request.onerror = function () { // This function is not working properly
    console.log("** An error occurred during the transaction");
  };
  request.send(data);
}

我也遇到了这种替代方法的问题:

try {
  request.open('post', 'http://localhost:8080/path/to/endpoint');
  request.send(data);
} catch (e) {
  console.log(e)
}

如何处理由 request.send() 引起的错误?

最佳答案

加载事件应该获取消息。看看那里的状态

request.addEventListener('load', (e) => {
  console.log(e.currentTarget.status) // or request.status
})

所以你可以做类似的事情

request.addEventListener('load', (e) => {
  if (request.status < 400) {
    dispatchIt()
  } else {
    displayError()
  }
})

关于javascript - 如何使用 XMLHttpRequest() 和 Javascript 处理 POST 请求错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60530184/

相关文章:

java - 在 Apache ServiceMix 中为 war 启用 CORS

c++ - 尝试使用 POST 将数据添加到我的 MySQL 数据库

php - 使用数组使用 foreach 填充其他变量

jquery - JavaScript 中可能存在明显的问题

jquery - 从 Django 中的 POST 请求读取多维数组

javascript - 在媒体查询中调用/触发 Foundation JS

Javascript window.open docx 文件/如何关闭窗口?

javascript - ECMAScript 对构造函数参数属性的建议

Javascript 数组高阶函数

http - 如何知道何时停止 HTTP 代理连接中的数据隧道