Javascript jquery post请求捕获失败的请求
在前端JS中,我向后端发送一个请求:Javascript jquery post请求捕获失败的请求,javascript,jquery,xmlhttprequest,Javascript,Jquery,Xmlhttprequest,在前端JS中,我向后端发送一个请求: $.post("/test", data, () => { console.log("received"); }) .done(() => { console.log("request finished"); }) .fail(function() { console.log("error");
$.post("/test", data, () => {
console.log("received");
})
.done(() => {
console.log("request finished");
})
.fail(function() {
console.log("error");
})
在后端,我故意导致请求失败:
app.post("/test", (req, res) => {
res.status(400).send("Error message");
})
显然,.fail
块没有捕获400错误。我后来尝试使用try-catch块:
try {
await $.post("/test", data, () => {
console.log("received");
})
}
catch (error) {
console.log(error);
}
尽管如此,错误还是出现了。我现在没有主意了。那么,如何捕获jquery post请求返回的错误?在浏览器devtools中检查响应。它是否真的将400 HTTP状态码返回到客户端?您也可以尝试404而不是400。
POSThttp://localhost:2000/test 400(错误请求)
这是给我的错误