0

I am trying to integrate a form made with React.js and a "backend side" to send the email from Express. I am not sure how to send formatted the form body, or just what method should I use in order to perform the HTTP request.

I have React.js and Express.js in two different folders. I have setted up express-mailer and used Postman to test requests and they work fine.

This is my Express code:

require('dotenv').config();
const express = require('express');
const logger = require('morgan');
const mailer = require('express-mailer');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('express-cors');
const server = express();


// Configuration
server.set('PORT', process.env.SERVER_PORT || 5000);
server.set('views', path.join(__dirname, 'views'));
server.set('view engine', 'jade');
server.use(logger('combined'));
server.use(bodyParser.urlencoded({ extended: false }));
server.use(cors({
    allowedOrigins: [
        'localhost:3000'
    ]
}));

mailer.extend(server, {
    from: process.env.EMAIL_FROM,
    host: process.env.EMAIL_HOST,
    secureConnection: process.env.EMAIL_SECURE,
    port: process.env.EMAIL_PORT,
    transportMethod: process.env.EMAIL_METHOD,
    auth: {
        user: process.env.EMAIL_FROM,
        pass: process.env.EMAIL_PASSWORD
    }
});

server.post('/contact', (req, res) => {
    server.mailer.send('email', {
        to: process.env.EMAIL_FROM,
        subject: `Contact ${req.body.subject}`,
        body: req.body
    }, err => {
        if (err) {
            console.log(err);
            res.send({ success: false, message: err });
        } else {
            res.send({ success: true, message: 'Message sent' });
        }
    });
});

server.listen(server.get('PORT'), () => {
    console.log('Server started on port', server.get('PORT'));
})

And this is my Form code:

import React, { Component } from 'react';
import {
    Container,
    Form,
    Button,
    Alert
} from 'react-bootstrap';

class Contact extends Component {
    constructor(props) {
        super(props);

        this.state = {
            modal: {
                visible: false,
                type: '',
                message: ''
            }
        };

        this.sendEmail = this.sendEmail.bind(this);
    }

    sendEmail(evt) {
        evt.preventDefault();

        const data = {
            name: evt.target.elements.name.value,
            email: evt.target.elements.email.value,
            subject: evt.target.elements.subject.value,
            message: evt.target.elements.message.value
        };

        fetch('http://localhost:5000/contact', {
            method: 'POST',
            body: JSON.stringify(data)
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                this.setState({
                    modal: {
                        type: 'success'
                    }
                });
            } else {
                this.setState({
                    modal: {
                        type: 'danger'
                    }
                });
            }
            this.setState({
                modal: {
                    visible: true,
                    message: data.message
                }
            });
        });

    }

    render() {
        return (
            <Container>
                <Alert variant={this.state.modal.type} dismissible style={{ display: this.state.modal.visible ? 'visible' : 'none' }}>
                    {this.state.modal.message}
                </Alert>
                <Form onSubmit={this.sendEmail}>
                    <Form.Group controlId="name">
                        <Form.Label>Name</Form.Label>
                        <Form.Control type="text" placeholder="Jhon" />
                    </Form.Group>
                    <Form.Group controlId="email">
                        <Form.Label>Email address</Form.Label>
                        <Form.Control type="email" placeholder="john@email.com" />
                    </Form.Group>
                    <Form.Group controlId="subject">
                        <Form.Label>Subject</Form.Label>
                        <Form.Control as="select">
                            <option>Budget</option>
                            <option>IT</option>
                        </Form.Control>
                    </Form.Group>
                    <Form.Group controlId="message">
                        <Form.Label>Message</Form.Label>
                        <Form.Control as="textarea" placeholder="Message" rows={10} />
                    </Form.Group>

                    <Button variant="primary" type="submit">Send</Button>
                </Form>
            </Container>

        );
    }
}

export default Contact;

I think I should get the req.body object somehow sent from React sendEmail() function to the Express side to process the data and then send the email.

So far I get an empty object in my "backend side" but maybe I should use http for Nodejs, axios or r2. Any ideas?

Martin Fernandez
  • 368
  • 5
  • 16

1 Answers1

1

Looks like your problem is a lack of name attributes on your html elements.

See this SO post for more details. But in short:

name is used by the server-side, this is necessary if you plan to process the field. id is only so label elements, when clicked and accessed by screen-readers, can trigger/invoke the form controls ( inputs, selects ).

Pytth
  • 4,008
  • 24
  • 29
  • Okay. I added `name` attribute. Then changed to `const data = new FormData(evt.target);` and then `body: data` in the request, but still getting this empty object. – Martin Fernandez Feb 01 '19 at 20:00