我是node.js的初学者。我想添加一个名字'和'部门'使用表格。一旦我点击提交,我正在安慰这两个名字'和'部门'但我得到了两个'是' undefined'。
我不知道我做了什么。任何一个人弄清楚并帮我控制名称和部门?
这是我的表格:
<form method="post" role="form" class="form-horizontal" enctype='multipart/form-data'>
<div class="form-group">
<label for="name"><input id='name' name='name' placeholder='Enter your name' type="text" ></label>
<label for="dept"><input id='dept' name='dept' placeholder='Enter your department here' type="text"></label>
<button type='submit' class="btn btn-default" id='submit'>Submit your Details</button>
<div>
</form>
这是我的app.js
var
http = require('http'),
express = require('express'),
routes = require('./routes'),
userList = require('./routes/list'),
path = require('path'),
app = express();
app.set('port', process.env.PROT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(app.router);
app.use(express.static(path.join(__dirname, 'static')));
app.get('/', routes.list);
app.get('/addList', userList.addList);
app.post('/addList', function(req, res){
var name = req.params.name;
var dept = req.params.dept;
console.log(name, dept);//getting undefined why?
});
http.createServer(app).listen(app.get('port'), function(){
console.log('successfuly initiated!');
});
更新了表单和app.js
形式:
<form method="post" role="form" class="form-horizontal" action="/addList">
<div class="form-group">
<label for="name"><input id='name' name='name' placeholder='Enter your name' type="text" ></label>
<label for="dept"><input id='dept' name='dept' placeholder='Enter your department here' type="text"></label>
<p><input type='submit' class="btn btn-default" id='submit' value='Submit your Details'/></p>
<div>
app.js
var
http = require('http'),
express = require('express'),
routes = require('./routes'),
userList = require('./routes/list'),
path = require('path'),
app = express();
app.set('port', process.env.PROT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(app.router);
app.use(express.static(path.join(__dirname, 'static')));
app.use(express.bodyParser()); //newly added
app.use(express.urlencoded()); //newly added
app.get('/', routes.list);
app.get('/addList', userList.addList);
app.post('/addList', function(req, res){
var name = req.body.name;
var dept = req.body.dept;
console.log(name, dept);
});
http.createServer(app).listen(app.get('port'), function(){
console.log('successfuly initiated!');
});
答案 0 :(得分:4)
您的表单缺少action="/addList"
属性
由于您使用方法POST
发布,因此您的值将在正文
var name = req.body.name;
var dept = req.body.dept;
表示在body中显示的值添加此中间件
app.use(express.bodyParser());
app.use(express.urlencoded());
app.use(app.router)
应该是你打电话的最后一件事。