我正在尝试处理 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/