首页 > 解决方案 > jquery post请求捕获失败的请求

问题描述

在前端 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");
})

显然,400 错误没有被.fail块捕获。我后来尝试使用 try catch 块:

  try {
    await $.post("/test", data, () => {
      console.log("received");
    })
  }
  catch (error) {
    console.log(error);
  }

尽管如此,错误还是消失了。我现在没有主意了。那么我应该如何捕获 jquery post 请求返回的错误呢?

标签: javascriptjqueryxmlhttprequest

解决方案


推荐阅读