Quentin Gérard Quentin Gérard - 7 months ago 71
Javascript Question

Cannot read property 'username' of undefined - Sending form data via email in Node.js

I'm trying to create a simple webpage when filling the contact form and pressing the submit button it should send a email.

I'm trying to use Node.js for this and I am getting this following error:

This is what I done so far.


Cannot read property 'username' of undefined


app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

app.post('/contact', function(req,res){
var mailOpts, smtpTrans;

smtpTransport = nodemailer.createTransport("SMTP",{
host: "smtp.gmail.com",
secureConnection: true,
port: 465,
auth: {
user: "myemail@gmail.com",
pass: "secret"
}
});

mailOpts = {
from: req.body.username + ' <' + req.body.email + '>',
to: 'qgerard.gerard@gmail.com',
subject: 'Website contact',
text: req.body.message
};


smtpTrans.sendMail(mailOpts, function(error, info){
if(error){
console.log(error);
}else{
console.log("Message sent: " + response.message);
}
});
console.log(req.body.username + ' <' + req.body.email + '>');
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});


module.exports = app;


index.js

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});

router.get('/contact', function(req, res, next){
res.render('contact', {title: 'Cantact'})
});

module.exports = router;


contact.jade

extends layout

block content
h1= title
p Welcome to #{title}
div.content
form(action="/contact", name="contactus", id="contactus", method="post")
fieldset
p
label(for="username") Name:
br
input(name="username", type="text", id="username")
p
label(for="email") Email:
br
input(name="email", type="email",id="email")
p
label(for="message") Message:
br
textarea(name="message", cols="40", rows="10", id="message")
p
input(name="submit", type="submit", value="Send", id="submit")


I have no idea what I'm missing here. If anyone knows how to fix this, please tell me what dependency I need (if any is required) and where I need to fix my error.

Kind Regards

Answer

You need to setup body-parser before you define your routes.

Move your express app configuration above your app.post('/contact') route:

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.post('/contact', function(req,res){
    //....
});