如何使用XMLHttpRequest()和Javascript处理POST请求错误
我试图处理HTTP请求引发的错误,但无法正确截获事件 POST 500(内部服务器错误) 我在页面上有一个放置区,用于接收文件并在服务器上解析它。当文件格式正确时,它运行良好,但我正在尝试处理由格式不正确的文档引起的错误 根据Mozilla文档,XMLHttpRequest有一个onerror函数,但当我尝试使用它时,它被绕过了,如下所示:如何使用XMLHttpRequest()和Javascript处理POST请求错误,javascript,http,post,error-handling,request,Javascript,Http,Post,Error Handling,Request,我试图处理HTTP请求引发的错误,但无法正确截获事件 POST 500(内部服务器错误) 我在页面上有一个放置区,用于接收文件并在服务器上解析它。当文件格式正确时,它运行良好,但我正在尝试处理由格式不正确的文档引起的错误 根据Mozilla文档,XMLHttpRequest有一个onerror函数,但当我尝试使用它时,它被绕过了,如下所示: _postRequest() { let files = this.files[0]; let data = new FormData(); l
_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()
}
})
request.addEventListener('load',(e)=>{
如果(请求状态<400){
dispatchIt()
}否则{
displayError()
}
})
简单的回答是,确保服务器发回一些东西。好的,onerror
部分用于处理客户端错误(无网络连接、无法访问主机等)。这是一个内部服务器错误,据我所知,Express正在发回res.status(500)。send(err.message)
。你说的“确保服务器发回一些东西”是什么意思