【问题标题】:How do I retrieve the error message from an API request [duplicate]如何从 API 请求中检索错误消息 [重复]
【发布时间】:2019-11-21 16:32:38
【问题描述】:

我正在构建一个身份验证项目。我不确定如何显示错误消息,以便我可以在屏幕上打印它们。例如,如果电子邮件地址已经注册,我怎么会得到这个错误。当我使用邮递员进行测试时,我能够看到错误消息,但我不确定如何使用 axios 来做到这一点。以下是用户输入已注册电子邮件时的代码。如何访问该消息

User.findOne({ email }).then(user => {
    if (user)
        return res.status(400).json({ msg: "Email already in use" });
});

【问题讨论】:

    标签: javascript node.js reactjs express axios


    【解决方案1】:

    发生的情况是,当您的服务器返回状态代码(如 400)时,它最终会在客户端代码(您正在执行请求的位置)中出现异常。有几种不同的方法可以解决这个问题,但最简单的方法是try/catch

    这是他们在GitHub 上建议的示例:

    /*
     * Handling Errors using async/await
     * Has to be used inside an async function
     */
    try {
        const response = await axios.get('https://your.site/api/v1/bla/ble/bli');
        // Success ?
        console.log(response);
    } catch (error) {
        // Error ?
        if (error.response) {
            /*
             * The request was made and the server responded with a
             * status code that falls out of the range of 2xx
             */
            console.log(error.response.data);
            console.log(error.response.status);
            console.log(error.response.headers);
        } else if (error.request) {
            /*
             * The request was made but no response was received, `error.request`
             * is an instance of XMLHttpRequest in the browser and an instance
             * of http.ClientRequest in Node.js
             */
            console.log(error.request);
        } else {
            // Something happened in setting up the request and triggered an Error
            console.log('Error', error.message);
        }
        console.log(error);
    }
    

    他们有更多的例子here。在其他一些 HttpClient 中,它们可以选择始终返回完整的 http 响应。我在 Axios 上没有看到该选项,但它可能只是隐藏在他们的文档中。

    【讨论】:

      【解决方案2】:

      查找有关 axios 文档的更多信息 - https://github.com/axios/axios/blob/master/README.md

      假设您有一个 api 端点,您可以在其中检查上述条件以获取唯一电子邮件地址,因此您可以使用 axios 向您的端点发送 post 请求并从服务器获取响应。在下面的示例中,将httpbin url 替换为您的端点并执行以获取响应。

      您可以访问您的msg,一条错误消息将发布在error 日志中。 处理 catch 部分中的任何异常。

      console.log(response.msg)

      axios.post('https://httpbin.org/post', {
          email: 'abc@xyz.com',
        })
        .then(function (response) {
          console.log(response);
        })
        .catch(function (error) {
          console.log(error);
        });
      <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.js"></script>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-10
        • 1970-01-01
        相关资源
        最近更新 更多