Alex Ironside
Alex Ironside

Reputation: 5059

Sending data with vanilla JS ajax and reading it with Node api

I have this code on my client side:

sendMail(e) {
    e.preventDefault();
    var name = document.getElementById('name').value;
    var contactReason = document.getElementById('contactReason').value;
    var email = document.getElementById('email').value;
    var additionalInfo = document.getElementById('additionalInfo').value;
    var body = {
        name: name,
        contactReason: contactReason,
        email: email,
        additionalInfo: additionalInfo,
    };
    console.log(body);
    fetch('http://localhost:4000/', {
        method: 'POST',
        body: body.toString(),
    }).then(r => console.log(r)).catch(e => console.log(e));
}

And this kind of works. It logs the object to the console, and sends something to the back end.

Here's my Node call:

var express = require('express');
var router = express.Router();
var cors = require('cors');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({extended: true}));
app.use(cors());
app.options('*', cors());

var a = '=';
router.post('/', (req, res, next) => {
        console.log('mailing');
        console.log(a);
        console.log(req.body);
        a += '=';
        var nodemailer = require('nodemailer');

        var transporter = nodemailer.createTransport({
            host: "smtp.gmail.com", // hostname
            auth: {
                user: '******',
                pass: '******'
            }
        });

        let mailOptions = {
            from: `${req.body.name} ${req.body.email}`, // sender address
            to: '[email protected]', // list of receivers
            subject: 'Email from UczSieApp contact form', // Subject line
            text: 'Hello world ', // plaintext body
            html: `
                        <h4>Imie: ${req.body.name}</h4>
                        <h4>Email: ${req.body.email}</h4>
                        <h4>Powod kontaktu: ${req.body.contactReason}</h4>
                        <p>Wiadomosc: ${req.body.additionalInfo}</p>
                        `
        };

        // send mail with defined transport object
        transporter.sendMail(mailOptions, function (error, info) {
            if (error) {
                return console.log(error);
            }

            console.log('Message sent: ' + info.response);
        });
    }
);
module.exports = router;

So what the code does right now:

The object is being created, something (not sure what exactly) is being send to Node back-end, and an email is being sent. But req.body is logged as {}.

What I want to do:

Read the values sent to the back-end as body and send an email with this data.

What am I missing?

Upvotes: 1

Views: 258

Answers (2)

Alex Ironside
Alex Ironside

Reputation: 5059

I used GET instead of POST and this solved my problems. It is kind of a cheat but it works.

Upvotes: 1

аlex
аlex

Reputation: 5698

should add to fetch

            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json'
            },

            body: JSON.stringify(body),

all correct code

frontend

sendMail(e) {
    e.preventDefault();
    var name = document.getElementById('name').value;
    var contactReason = document.getElementById('contactReason').value;
    var email = document.getElementById('email').value;
    var additionalInfo = document.getElementById('additionalInfo').value;
    var body = {
        name: name,
        contactReason: contactReason,
        email: email,
        additionalInfo: additionalInfo,
    };
    console.log(body);
    fetch('http://localhost:4000/', {
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },

        body: JSON.stringify(body),
        method: 'POST',
    }).then(r => console.log(r)).catch(e => console.log(e));
}

backend

var express = require('express');
var router = express.Router();
var cors = require('cors');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({extended: true}));
app.use(cors());
app.options('*', cors());

var a = '=';
router.post('/', (req, res, next) => {
        console.log('mailing');
        console.log(a);
        console.log(req.body);
        a += '=';
        var nodemailer = require('nodemailer');

        var transporter = nodemailer.createTransport({
            host: "smtp.gmail.com", // hostname
            auth: {
                user: '******',
                pass: '******'
            }
        });

        let mailOptions = {
            from: `${req.body.name} ${req.body.email}`, // sender address
            to: '[email protected]', // list of receivers
            subject: 'Email from UczSieApp contact form', // Subject line
            text: 'Hello world ', // plaintext body
            html: `
                        <h4>Imie: ${req.body.name}</h4>
                        <h4>Email: ${req.body.email}</h4>
                        <h4>Powod kontaktu: ${req.body.contactReason}</h4>
                        <p>Wiadomosc: ${req.body.additionalInfo}</p>
                        `
        };

        // send mail with defined transport object
        transporter.sendMail(mailOptions, function (error, info) {
            if (error) {
                return console.log(error);
            }

            console.log('Message sent: ' + info.response);
        });
    }
);
module.exports = router;

Upvotes: 0

Related Questions