无法读取未定义的 属性 'username' - 在 Node.js 中通过电子邮件发送表单数据

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

我正在尝试创建一个简单的网页,在填写联系表格并按下提交按钮时它应该会发送一封电子邮件。

我正在尝试为此使用 Node.js,但出现以下错误:

这是我到目前为止所做的。

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")

我不知道我在这里错过了什么。如果有人知道如何解决这个问题,请告诉我我需要什么依赖项(如果需要的话)以及我需要在哪里修复我的错误。

亲切的问候

您需要先设置 body-parser,然后再定义路线。

将您的 Express 应用配置移至 app.post('/contact') 路线之上:

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){
    //....
});

在注册 post 之后注册 bodyparser。将 app.use 行移到 app.post 之前,我认为它会起作用。