从expressJS中的POST方法获取值
我正在尝试在我的应用程序中注册用户。这是 HTML 代码:
<form id="registration_form" action="register" onsubmit="return validateForm();" method="post">
Username: <input type="text" id="username" name="user[name]" /><br />
Password: <input type="password" id="password" name="user[pass]" /><br />
Repeat Password: <input type="password" id="password_repeat" name="user[pass]" /><br />
Email: <input type="text" id="email" name="user[email]" /><br />
<button type="submit" value="Register">Register</button>
<div id="error_registration" style="color: red;">
</div>
</form>
我在服务器中所做的就是获取名称、通行证和电子邮件的值。
var express = require('express')
, app = express.createServer(
express.logger(),
express.cookieParser(),
express.session({ secret: 'keyboard cat' })
)
, io = require('socket.io').listen(app)
, mongoose = require('mongoose')
, schemas = require('./schemas')
, Schema = mongoose.Schema;
app.listen(80);
app.configure(function(){
app.use(express.bodyParser());
});
[...]
app.post('/register', function (req, res) {
registerUser(req, function(result){
//do something
var username = req.body.username;
});
});
我的问题是:为什么用户名总是未定义?我读错了吗?那我该怎么办呢?
谢谢
I'm trying to register a user in my application. This is the HTML code:
<form id="registration_form" action="register" onsubmit="return validateForm();" method="post">
Username: <input type="text" id="username" name="user[name]" /><br />
Password: <input type="password" id="password" name="user[pass]" /><br />
Repeat Password: <input type="password" id="password_repeat" name="user[pass]" /><br />
Email: <input type="text" id="email" name="user[email]" /><br />
<button type="submit" value="Register">Register</button>
<div id="error_registration" style="color: red;">
</div>
</form>
What I do in the server is taking the values of name, pass and email.
var express = require('express')
, app = express.createServer(
express.logger(),
express.cookieParser(),
express.session({ secret: 'keyboard cat' })
)
, io = require('socket.io').listen(app)
, mongoose = require('mongoose')
, schemas = require('./schemas')
, Schema = mongoose.Schema;
app.listen(80);
app.configure(function(){
app.use(express.bodyParser());
});
[...]
app.post('/register', function (req, res) {
registerUser(req, function(result){
//do something
var username = req.body.username;
});
});
My question is: why username is always undefined? Am I reading it in the wrong way? How should I then?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的变量是用户而不是用户名。
看:
..input type="text" id="username" name="user[name]" ..
另外,您也可以随时执行 console.log(req.body) 来查看 POST 变量在终端中。
Your variable is user not username.
Look:
..input type="text" id="username" name="user[name]" ..
Also you can always do console.log(req.body) to see the POST vars in the terminal.