如何修复TypeError:无法从Express Nodemailer读取属性"name"

jem*_*oii 4 forms node.js express handlebars.js nodemailer

所以我想说我一直在寻找这个问题的答案,我也尝试过console.log我的req.body帖子,我一直都没有定义.所以我觉得我丢失了我发送的表单中的数据,我不确定我做错了什么.所以时间显示一些代码.

作为注释:我正在使用Handlebars进行Express Setup.

app.js

var express    = require('express'),
    exphbr     = require('express3-handlebars'), // "express3-handlebars"
    nodemailer = require('nodemailer'),
    helpers    = require('./lib/helpers'),

    app = express(), handlebars;

// Create `ExpressHandlebars` instance with a default layout.
handlebars = exphbr.create({
    defaultLayout: 'main',
    helpers      : helpers,
    extname      : '.html',

    // Uses multiple partials dirs, templates in "shared/templates/" are shared
    // with the client-side of the app (see below).
    partialsDir: [
        'views/shared/',
        'views/partials/'
    ]
});

// Register `hbs` as our view engine using its bound `engine()` function.
app.engine('html', handlebars.engine);
app.set('view engine', 'html');

require("./routes")(app, express, nodemailer);

app.listen(3000);
Run Code Online (Sandbox Code Playgroud)

routes.js

module.exports = function (app, express, nodemailer) {

    // set up the routes themselves
    app.get('/', function (req, res) {
        res.render('home', {
            title: 'Larry King Orchestra'
        });
    });

    // I cut out a majority of my routes to make this easier to read.

    // SEND EMAIL FROM FORM
    app.post('/', function (req, res) {
        console.log("WTF");
        console.log(req.body.name);
        console.log(req.body.email);

        var mailOpts, smtpTrans;

        //Setup nodemailer transport, I chose gmail. Create an application-specific password to avoid problems.
        smtpTrans = nodemailer.createTransport('SMTP', {
            service: 'Gmail',
            auth: {
                user: "email@gmail.com",
                pass: "password" 
            }
        });

        //Mail options
        mailOpts = {
            from: req.body.email, //grab form data from the request body object
            to: 'anotheremail@gmail.com',
            subject: 'LKO Contact Form',
            html: 'From: ' + req.body.name + ' &lt;' + req.body.email + '&gt; <br>Phone: ' + req.body.tel + '<br>Date of Event: ' + req.body.date + '<br>Location: ' +  req.body.location + '<br>Details &amp; Comments:<br>' + req.body.message + '<br><br><p>Email form provided by <a href="http://www.wavamedia.com/">WavaMedia</a>.'
        };

        smtpTrans.sendMail(mailOpts, function (error, response) {
            //Email not sent
            if (error) {
                res.render('home', { 
                    title: 'Larry King Orchestra', 
                    msg: 'Error occured, message not sent.', 
                    err: true, 
                    page: 'home' 
                });
            }
            //Yay!! Email sent
            else {
                res.render('home', { 
                    title: 'Larry King Orchestra', 
                    msg: 'Message sent! Thank you.', 
                    err: false, 
                    page: 'home'
                });
            }
        });
    });

    // STATIC ROUTE FOR ASSESTS
    app.use(express.static('assests/'));
};
Run Code Online (Sandbox Code Playgroud)

我将把手扩展名重命名为.html,并且我使用partials的主要布局.SO app.get('/')将此下一个文件显示为部分文件,并在页面上呈现它.

contact.html

<form class="contact" action="/" method="post">
    <label for="name">Name</label>
    <input type="name" name="name" id="name">

    <label for="email">Your Email (required)</label>
    <input type="email" name="email" id="email">

    <label for="tel">Phone Number</label>
    <input type="tel" name="tel" id="tel">

    <label for="date">Date of Your Event</label>
    <input type="date" name="date" id="date">

    <label for="location">Venue/Location</label>
    <input type="location" name="location" id="location">

    <label for-"message">Details &amp; Comments</label>
    <textarea name="message" id="message" rows="3"></textarea>

    <input type="submit" name="submit" id="submit" value="Send" class="btn btn-default">
</form>
Run Code Online (Sandbox Code Playgroud)

我的错误:

TypeError: Cannot read property 'name' of undefined at c:\xampp\htdocs\lko\routes.js:129:26 at callbacks (c:\xampp\htdocs\lko\node_modules\express\lib\router\index.js:164:37) at param (c:\xampp\htdocs\lko\node_modules\express\lib\router\index.js:138:11) at pass (c:\xampp\htdocs\lko\node_modules\express\lib\router\index.js:145:5) at Router._dispatch (c:\xampp\htdocs\lko\node_modules\express\lib\router\index.js:173:5) at Object.router (c:\xampp\htdocs\lko\node_modules\express\lib\router\index.js:33:10) at next (c:\xampp\htdocs\lko\node_modules\express\node_modules\connect\lib\proto.js:193:15) at Object.expressInit [as handle] (c:\xampp\htdocs\lko\node_modules\express\lib\middleware.js:30:5) at next (c:\xampp\htdocs\lko\node_modules\express\node_modules\connect\lib\proto.js:193:15) at Object.query [as handle] (c:\xampp\htdocs\lko\node_modules\express\node_modules\connect\lib\middleware\query.js:45:5)
Run Code Online (Sandbox Code Playgroud)

所以我不确定我的代码出错了.我相信表单是将数据发送到我的节点应用程序,但是它在哪里,我不确定.我已经设置了post方法,到目前为止没有运气:(我已经尝试了几天.我也安装了nodemailer.我重新启动了服务器,更新了节点和npm.

JavaScript Node Guru Masters,只有你可以给我看灯!感谢阅读所有这一切,非常棒!

mrc*_*cni 8

app.use(express.bodyParser());
Run Code Online (Sandbox Code Playgroud)

将其添加到您的app.js,这是从帖子数据表单中获取信息的内容.


Las*_*apa 5

您必须为此需要主体解析器包。
首先,您必须使用npm安装它。

$ npm install --save body-parser
Run Code Online (Sandbox Code Playgroud)

然后在您的js文件中要求。

var bodyParser = require('body-parser');
Run Code Online (Sandbox Code Playgroud)

然后添加解析器。当您使用html post方法时,它将urlencoded用作编码类型。为此添加此行。

var urlencodedParser = bodyParser.urlencoded({ extended: false });
Run Code Online (Sandbox Code Playgroud)

(如果使用json,则必须使用json bodyParser.json()代替)
现在将具有编码类型的解析器添加到app.post方法中,如下所示。

app.post('/',urlencodedParser, function (req, res) {
    //your code here
});
Run Code Online (Sandbox Code Playgroud)