Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jquery post请求捕获失败的请求_Javascript_Jquery_Xmlhttprequest - Fatal编程技术网

Javascript jquery post请求捕获失败的请求

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");

在前端JS中,我向后端发送一个请求:

  $.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(错误请求)
这是给我的错误