提交表单发现表单中的属性是undefined
发布于 15小时前 作者 taihangy 40 次浏览 来自 问答

刚开始学习Nodejs,跟着教程做blog,但是做到注册新用户,输入用户名,密码之类,点击注册后,直接报错: TypeError: Cannot read property ‘username’ of undefined at /Users/yetaihang/WebstormProjects/blog/routes/index.js:18:28 at Layer.handle [as handle_request] (/Users/yetaihang/WebstormProjects/blog/node_modules/express/lib/router/layer.js:95:5) at next (/Users/yetaihang/WebstormProjects/blog/node_modules/express/lib/router/route.js:131:13) at Route.dispatch (/Users/yetaihang/WebstormProjects/blog/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/Users/yetaihang/WebstormProjects/blog/node_modules/express/lib/router/layer.js:95:5) at /Users/yetaihang/WebstormProjects/blog/node_modules/express/lib/router/index.js:277:22 at Function.process_params (/Users/yetaihang/WebstormProjects/blog/node_modules/express/lib/router/index.js:330:12) at next (/Users/yetaihang/WebstormProjects/blog/node_modules/express/lib/router/index.js:271:10) at expressInit (/Users/yetaihang/WebstormProjects/blog/node_modules/express/lib/middleware/init.js:33:5) at Layer.handle [as handle_request] (/Users/yetaihang/WebstormProjects/blog/node_modules/express/lib/router/layer.js:95:5)

我的表单注册页面如下: <%- include header %>

<form method="post" enctype="multipart/form-data"> 用户名: <input type="text" name="username" required>
密码: <input type="password" name="password" required>
确认密码:<input type="password" name="password-repeat" required>
邮箱: <input type="email" name="email" required>
<input type="submit" value="注册"> </form> <%- include footer %>

我的后端服务器处理post代码如下:

app.post('/reg’, function (req, res) { var username = req.body[‘username’]; var password = req.body[‘password’]; var password_re = req.body[‘password-repeat’]; //检验用户两次输入的密码是否一致 if (password_re != password) { req.flash('error’, ‘两次输入的密码不一致!’); return res.redirect(‘/reg’);//返回主册页 } //生成密码的 md5 值 var md5 = crypto.createHash(‘md5’), password = md5.update(req.body.password).digest(‘hex’); var newUser = new User({ name: req.body.name, password: password, email: req.body.email }); //检查用户名是否已经存在 User.get(newUser.name, function (err, user) { if (user) { req.flash('error’, ‘用户已存在!’); return res.redirect(‘/reg’);//返回注册页 } //如果不存在则新增用户 newUser.save(function (err, user) { if (err) { req.flash('error’, err); return res.redirect(‘/reg’);//注册失败返回主册页 } req.session.user = user;//用户信息存入 session req.flash('success’, ‘注册成功!’); res.redirect(‘/’);//注册成功后返回主页 }); }); });

在第一步var username = req.body[‘username’];就发生了错误,因为小弟刚开始学,不知道怎么样才能debug?

1 回复

先 console 一下 req.body form 的 action 有么? var username = req.body.username;

回到顶部