使用Mongodb和node.js在一个页面中处理多个表单

我在同一页面上login和注册。 我已经指定了两个不同的path发布数据,但是当我点击registry单末尾的注册button时,它保存了login表单input(这是没有的)? 我看了这个问题( 多个表单和一个处理页面 )。 它如何与节点工作,这意味着我必须创build一个模块为不同的forms?

这是我的代码。 我最后还有一个小脚本也是因为我的引导模板的滑块function与提交function冲突。

<h2>Register<h2> <form method="POST" action="/samples"> <input type="text" name="fullName" id="fullName" class="input-lg " placeholder="your full name" data-required="true"> <input type="text" name="age" id="age" class="input-lg" placeholder="age"> <input type="text" name="city" id="city" class="input-lg" placeholder="Your City"> <input type="text" name="job" class="input-lg" placeholder="Your Job"> <input type="text" name="username" class="input-lg " placeholder="prefered username" data-required="true"> <input type="password" name="password" class="input-lg" placeholder="Password"> <input type="email" name="email" class="input-lg " placeholder="your email" data-required="true"> <button type="submit" class="btn btn-primary">Sign in</button> </form> <h2>Login!</h2> <form method="POST" action="/dashboard"> <hr class="colorgraph"> <input type="email" name="emaillog" class="input-lg " placeholder="your email" data-required="true"> <input type="password" name="passwordlog" class="input-lg" placeholder="Password"> <button type="submit" class="btn btn-primary">Sign in</button> </form> <script> $('button').click( function() { $('form').submit(); }); </script> 

谢谢你的帮助

那么首先,因为你有两种forms,你必须指定在button上单击提交哪个表单。 现在任何button点击都会提交第一个表单。 给第一个表单的提交button类registerButton和第二个表单的提交类loginButton 。 我也build议给你的表格上课。 一个是registerForm ,另一个是loginForm 。 然后更改您的HTML以反映更改

 <form method="POST" action="/samples" class="registerForm"> ... <button type="submit" class="btn btn-primary registerButton">Sign in</button> <form method="POST" action="/dashboard" class="loginForm"> ... <button type="submit" class="btn btn-primary loginButton">Log in</button> 

然后改变你的JavaScript到这个:

  $('button.registerButton').click( function() { $('form.registerForm').submit(); }); $('button.loginButton').click( function() { $('form.loginForm').submit(); }); 

现在您可以将两个表单提交给两个不同的路线
一种forms是去样品 ,另一种去仪表板 ,所以在你的服务器(在节点),你可以检查它是哪个路线。 我会build议使用其中一个Node框架来处理您的应用程序。 你可以试试快递 。 这将大大简化您的路线工作。 这将允许你写这样简单的路线:

 app.post('/samples', function(req, res){ // check register form // res.send('user' + req.body); }); app.get('/dashboard', function(req, res){ // check login form // res.send('user' + req.body); }); 

您可以在这里阅读更多关于Express的build议列表。