【问题标题】:Axios does not return proper error messageAxios 没有返回正确的错误信息
【发布时间】:2021-12-16 23:44:24
【问题描述】:

我有以下代码 sn-p 向我的后端发出 api 请求以取回 json 中的用户对象,如果用户未通过身份验证,则返回状态代码 401,以及它应该收到一条消息的状态代码.

   <script>
  axios
    .get("http://localhost:5000/get-authenticated-user")
    .then(function (response) {
      // handle success
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });
</script>

我的 API 路由如下所示:

router.get("/get-authenticated-user", (req, res) => {
  if (req.user) {
    res.json({ user: req.user });
  }

  res.status(401).json({ err: "Not authenticated" });
});

但是,当用户未通过身份验证时,它只会返回以下错误消息(在 catch 块中),而不是从我的 API 提供的“未通过身份验证”消息。

Error: Request failed with status code 401
    at e.exports (createError.js:16)
    at e.exports (settle.js:17)
    at XMLHttpRequest.E (xhr.js:66)

身份验证正常工作,只是用户未通过身份验证时错误消息未正确显示。我已经为此苦苦挣扎了一段时间,有人有想法吗?

【问题讨论】:

    标签: node.js api axios


    【解决方案1】:

    您可以通过检查错误回调中的error.response.data 来检索 401 响应正文数据:

    <script>
      axios
        .get("http://localhost:5000/get-authenticated-user")
        .then(function (response) {
          // handle success
          console.log(response);
        })
        .catch(function (error) {
          console.log(error.response.data);
        });
    </script>
    

    在您的情况下,它将显示您从 Express 服务器返回的具有 err 字段的对象。

    【讨论】:

    • @Detlapuite hanks 这似乎有效,为什么当我只是 console.log 错误对象时这不显示?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    相关资源
    最近更新 更多