为什么我不能设法从html表单发送数据发送到express.js?

时间:2015-05-25 00:41:53

标签: html node.js forms post express

我有这个server.js的代码,我真的很新。 我尝试将html表单发送到node.js服务器(localhost)

server.js

//initialing the website


var express = require('express');
var app = express();

app.get('/',function(req, res){//get,put,post,delete   

res.sendFile('C:\\work\\translator\\startbootstrap-freelancer-1.0.3\\index.html');
app.use("/css", express.static(__dirname + '/startbootstrap-freelancer-1.0.3/css'));
app.use("/img", express.static(__dirname + '/startbootstrap-freelancer-1.0.3/img'));
app.use("/font-awesome", express.static(__dirname + '/startbootstrap-freelancer-1.0.3/font-awesome'));
app.use("/js", express.static(__dirname + '/startbootstrap-freelancer-1.0.3/js'));
app.use("/less", express.static(__dirname + '/startbootstrap-freelancer-1.0.3/less'));
app.use("/mail", express.static(__dirname + '/startbootstrap-freelancer-1.0.3/mail'));
app.use("/fonts", express.static(__dirname + '/startbootstrap-freelancer-1.0.3/fonts'));
    });


var server = app.listen(3000, function () {

  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);

});


//sending mail with gmail


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

var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({

    service: 'gmail',
    auth: {
        user: 'my_email',
        pass: 'my_password'
    }
});

  transporter.sendMail({
    from:  'user@email.com',
    to: 'myemail@email.com',
    subject: 'contact',
    text:  'hello world'
});
 });

Html表格

<form name="sentMessage" action="/contact" method="post" id="contact" novalidate>
<input type="text" class="form-control" name="name">
<input type="email" class="form-control" name="email">
<input type="tel" class="form-control" name="phone">
<textarea rows="5" class="form-control" name="message"></textarea>
<button type="submit" class="btn btn-success btn-lg">send</button>

我尝试了req.paramsreq.body.email和所有类型的事情来收到电子邮件字段中的电子邮件,但它说:“email undefiend”,似乎某种程度上server.js没有得到值/参数或其他东西......

1 个答案:

答案 0 :(得分:0)

Express非常简单。您需要添加正文解析器中间件来处理表单。像这样:

https://github.com/expressjs/body-parser