0

I am having trouble receiving a response from my backend (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!")
}

The above will send the errors that were encountered via res.status(400) line.

When I use PostMan to send a POST method I receive the correct response messages. see below.

enter image description here

However when I use Axios on my frontend I am not receiving a response

FrontEnd

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

enter image description here

2 Answers 2

1

In the catch block, try this:

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

I tested it on my browser, it gives me the error message: enter image description here

Sign up to request clarification or add additional context in comments.

Comments

0

Try console.log(e.message) to get the response message.

2 Comments

just says "Request failed with status code 400"
Hm. Perhaps you need to parse the response to use it. How about e.json()?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.