【问题标题】:Not receiving response errors from Backend RestAPI using Axios使用 Axios 未收到来自 Backend Rest API 的响应错误
【发布时间】:2021-06-28 11:27:05
【问题描述】:

我在接收来自后端 (Node.js Express RestAPI) 的响应时遇到问题。

exports.send = function(req, res) {
    console.log("sent function running!")
    let contact = new Contact(req.body)
    contact.send()
    if (contact.errors.length) {
        res.status(400).send(JSON.stringify(contact.errors));
        return;
    }
    res.send("Message Sent!")
}

以上将通过 res.status(400) 行发送遇到的错误。

当我使用 PostMan 发送 POST 方法时,我会收到正确的响应消息。见下文。

但是,当我在前端使用 Axios 时,我没有收到响应

前端

const axios = require('axios')


class ContactForm {
    constructor() {
        this.name = document.getElementById("fname").value;
        this.email = document.getElementById("email").value;
        this.message = document.getElementById("message").value;
        this.submitButton = document.getElementById("submitMessage")
        this.events();
    }

    events() {
        this.submitButton.addEventListener("click", (e) => this.sendMesage(e))
    }

    sendMesage(e) {
        e.preventDefault()
        axios.post('http://localhost:5000/api/contact/send', {
            name: this.name,
            email: this.email,
            message: this.message
        }).then(res => {
            console.log(res)
        }).catch(e => {
            console.log("ran into errors")
            console.log(e)
        })

    }

}

export default ContactForm

【问题讨论】:

    标签: javascript node.js express axios


    【解决方案1】:

    在 catch 块中,试试这个:

      .catch(function (error) {
           console.log(error.response.data);
      });
    

    我在浏览器上对其进行了测试,它给了我错误消息:

    【讨论】:

      【解决方案2】:

      尝试console.log(e.message) 获取响应消息。

      【讨论】:

      • 只是说“请求失败,状态码 400”
      • 嗯。也许您需要解析响应才能使用它。 e.json() 怎么样?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-03
      • 2020-07-25
      • 2021-05-27
      • 1970-01-01
      • 1970-01-01
      • 2017-05-20
      • 2023-04-07
      相关资源
      最近更新 更多