Dariun
Dariun

Reputation: 347

req.body.name is not defined - Nodemailer ejs

I saw some problems which are close to mine but not exactly the same so my issue is I got a ejs template with a Form attribut and I want to send the input to a mail so I declare all input with name="xyz" and inside the routes.get: req.body.conSurname, conName: req.body.conName,. So my post route looks like this.

router.post('/contact/send', (req, res) => {
    // Nodemailer
    let transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: '[email protected]',
            pass: '******'
        }
    });
    const mailOptions = {
        from: '[email protected]', 
        to: '[email protected]', 
        subject: 'New Mail', 
        html: '<h2>Mail from: '+ req.body.conSurname + ' ' + conName + '</h2>'
    };
    transporter.sendMail(mailOptions, function (err, info) {
        if (err)
            console.log(err)
        else
            console.log(info);
    });
    res.redirect('/contact');
})

If I send the formular it throws ReferenceError: conSurname is not defined but if I log one attrubut it shows me the correct value from the input. Where is the error?

Upvotes: 0

Views: 212

Answers (1)

Guerric P
Guerric P

Reputation: 31835

That's because you have to import the json middleware like this:

var express = require('express');
var app = express();
app.use(express.json());

Then your express server will deserialize JSON bodies when receiving requests with the Content-Type: application/json header, and your code will work correctly.

Upvotes: 1

Related Questions