Home > Net >  Unable to send data through the body using react and node
Unable to send data through the body using react and node

Time:08-25

I'm trying to use nodemailer in my web app to sends an email to my email with a message attached to it. Right now, I'm trying to connect my frontend and backend so that my frontend can send data to the backend and ultimately the backend will email the message. I'm able to send a post request to my api endpoint in the backend called /api/sendmail but whatever I send through the body doesn't get passed through to the backend. Here is my frontend code:

import React from 'react'
 
class ContactForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = { message: '' };
  }
 
  handleChange = (event) => {
    this.setState({[event.target.name]: event.target.value});
    console.log(this.state.message)
  }
 
  handleSubmit = (event) => {
    alert('A form was submitted: '   this.state.message);
 
    fetch('/api/sendmail', {
        method: 'POST',
        // We convert the React state to JSON and send it as the POST body
        body: JSON.stringify(this.state)
      }).then(function(response) {
        console.log(response)
        return response.json();
      });
 
    event.preventDefault();
}
 
  render() {
    return (
        <div className="contact-page-body">
            <form onSubmit={this.handleSubmit}>
                <label>
                    Message:
                    <input type="text" value={this.state.message} name="message" onChange={this.handleChange} />
                </label>
                <input type="submit" value="Submit" />
            </form>
        </div>
      
    );
  }
}
 
export default ContactForm;

Here is my backend api endpoint:

// nodemailer config
const nodemailer = require("nodemailer")

const transporter = nodemailer.createTransport({
    service: "gmail",
    auth: {
        user: process.env.AUTH_EMAIL,
        pass: process.env.AUTH_PASS // generated app password
    }
})

app.post("/api/sendmail", (req, res) => {
    console.log(res)
    const {message} = req.body;

    const mailOptions = {
        from: process.env.AUTH_EMAIL,
        to: '[email protected]',
        subject: 'Community Partnership Project Contact Form Inquiry',
        text: message
    }

    transporter.sendMail(mailOptions)
        .then(() => {
            res.json({
                status: "SUCCESS",
                message: "Message sent successfuly"
            })
        })
        .catch((error) => {
            //An error occured
            console.log(error);
            res.json({status: "FAILED", message: "An error occured!"})
        })
})

When I try to log out the body request from the backend I just get an empty object even though in the frontend it clearly shows that I sent something in it. How do I fix this?

CodePudding user response:

You need to add the content-type header to your API call:

fetch('/api/sendmail', {
        method: 'POST',
        body: JSON.stringify(this.state),
        headers: {'Content-Type': 'application/json'},
      }).then(function(response) {
        console.log(response)
        return response.json();
      });
  • Related