Node.js – 提交表单不控制表单值

我是node.js的初学者。 我正在尝试使用表单添加“名称”和“部门”。 一旦我点击提交,我安慰'名称'和'部门',但我得到'两'是'未定义'。

我不知道我在做什么。 任何一个数字,并帮助我安慰名称和部门?

这是我的forms:

<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!'); }); 

       

网上收集的解决方案 "Node.js – 提交表单不控制表单值"

您的表单缺lessaction="/addList"属性

也因为你使用POST方法发布你的值将在正文上

 var name = req.body.name; var dept = req.body.dept; 

为了出现在身上的值添加这个中间件

 app.use(express.bodyParser()); app.use(express.urlencoded()); 

app.use(app.router)应该是你最后一次调用的东西。