Node.js(Express)表格在提交时清除

我正在使用Node.js(使用Express)开发一个非常基本的registry单,我正在试图find提供基本表单validation的最简单的方法。 我已经去了“快速确认器”,这似乎做得很好。 但是,我的目标是简单地显示所需的任何validation消息,并保留用户input的值。

看来请求信息没有回到res.render,我想这是有道理的。 然而,我已经到处看到了我能想到的,我找不到任何参考,讨论如何在显示错误消息后填充表单字段。

以下是描述我的方法的小片段:

post: function(req, res){ var userName = req.body.username; var password = req.body.password; //Validate input req.assert("username", 'Invalid email address.').isEmail(); req.assert("password", 'Password cannot be empty.').notEmpty(); req.assert("passwordConfirm", 'Passwords entered do not match!').equals(password); //Make sure we have no validation errors var pageErrors = req.validationErrors(); if(!pageErrors) { userModel.CreateUser(userName, password, function(err){ if(err) { //there was a problem inserting new user... probably already exists //will need to check the error to confirm var dbErrorMessage = "Could not insert record into database!"; if(err.code === 11000) { //this is a duplicate entry dbErrorMessage = "A user with that email address already exists!"; } res.render('register.html', { pageErrors: [{msg: dbErrorMessage }]}); } else { res.render('register.html', { successMessage: successMessage }); } }); } else { res.render('register.html', { pageErrors: pageErrors }); } 

不幸的是,你必须手动重新填写表单。 如果您收到任何页面错误,您将传回表单值到视图。

  if(!pageErrors) { // ... } else { res.render('register.html', { pageErrors: pageErrors, userName: userName }); } 

在你看来,你会做一个简单的检查,看看他们是否有任何错误,并据此重新填充。 你将不得不跟踪每个表单字段产生的错误。

 <% if (userNameError) { %> <input type="text" name="userName" value="<%- userName %>" /> <% } else { %> <input type="text" name="userName" /> <% } %> 

另一个stream行的方法是通过ajax发送你的表单到服务器,并做所有你的validation。 如果出现错误,input的表单数据将保留,您将显示错误,否则在成功login后redirect。 以下是如何使用javascript提交表单的示例。

 $("#login-button").live("submit", function (e) { // this will prevent the form from being uploaded to the server the conventioanl way e.preventDefault(); // the form data var data = $(this).serialize(); // this logs the user in $.ajax({ type: 'POST', url: BASE_URL + '/login', data: data, dataType: 'json', success: function (data, status) { // successful }, }); // superfluous fallback return false; }); 

你正在使用一个简单的方法

 app.use(express.bodyParser()) and app.use(expressValidator()); 

你可以使用req.body

 res.render('register.html', { pageErrors: pageErrors, validated: req.body }); 

我不确定你正在使用哪种模板语言,但你可以做类似

 <input type="text" name="userName" value="<%= pageErrors.userName.value || validated.userName %>" /> 

如果没有问题,则会返回正确的input,如果需要更正,则返回错误的input。

您可以使用connect-flash完成此操作

下面是不同文件中的代码片段,以便在用护照进行注册时validation失败时,将用户input的值返回到表单中。

运行以下命令将新包添加到package.json中

 npm install connect-flash --save 

app.js

 var flash = require('connect-flash'); app.use(flash()); // add this above passport initialize app.use(passport.initialize()); app.use(passport.session()); 

config / passport.js (请注意表单数据加载到Flash中)

 passport.use('local.signup', new LocalStrategy({ usernameField: 'email', passwordField: 'password', passReqToCallback: true }, function (req, email, password, done) { req.checkBody('first_name', 'Firstname is missing').notEmpty(); req.checkBody('last_name', 'Lastname is missing').notEmpty(); req.checkBody('email', 'Invalid email').notEmpty().isEmail(); req.checkBody('password', 'Password is too short. Minimum size is 6.').notEmpty().isLength({min:6}); req.checkBody('confirm_password', 'Password and confirm password didn\'t not match').equals(req.body.password); var errors = req.validationErrors(); if (errors) { var messages = []; errors.forEach(function(error) { messages.push(error.msg); }); req.flash('formdata', req.body); // load form data into flash return done(null, false, req.flash('error', messages)); } User.findOne({'email': email}, function (err, user) { if (err) { req.flash('formdata', req.body); // load form data into flash return done(err); } if (user) { req.flash('formdata', req.body); // load form data into flash return done(null, false, {message: 'Email is already in use.'}); } var newUser = new User(); newUser.first_name = req.body.first_name; newUser.last_name = req.body.last_name; newUser.email = email; newUser.password = newUser.encryptPassword(password); newUser.save(function(err, result) { if (err) { return done(err); } return done(null, newUser); }); }); })); 

routes / index.js (请重点关注表单数据在flash中加载回variables)

  router.get('/signup', function (req, res, next) { var messages = req.flash('error'); var formdata = req.flash('formdata'); // Get formdata back into a variable res.render('user/signup', {csrfToken: req.csrfToken(), messages: messages, // pass it here to access in view file hasErrors: messages.length > 0, formData: formdata[0] }); }); router.post('/signup', passport.authenticate('local.signup', { badRequestMessage: 'Please fill the form with all details', failureRedirect: '/user/signup', failureFlash: true }), function (req, res, next) { if (req.session.oldUrl) { var oldUrl = req.session.oldUrl; req.session.oldUrl = null; res.redirect(oldUrl); } else { res.redirect('/user/profile'); } }); 

views / signup.hbs (请关注input元素中的值)

 <form class="wow fadeInUp animated" data-wow-delay=".7s" action="/user/signup" method="post" > <input type="text" placeholder="First Name" name="first_name" value="{{ formData.first_name }}"> <input type="text" placeholder="Last Name" name="last_name" value="{{ formData.last_name }}"> <input type="text" class="email" placeholder="Email Address" name="email" value="{{ formData.email }}"> <input type="password" name="password" value="" class="lock" placeholder="Password"> <input type="password" name="confirm_password" value="" class="lock" placeholder="Confirm Password"> <input type="hidden" name="_csrf" value="{{ csrfToken }}"> <input type="submit" name="Register" value="Register"></form> 

希望这可以帮助。

为所有input设置一个variables,例如

 var inputData = { firstname : req.body.firstname, lastname : req.body.lastname, email : req.body.email, username : req.body.username, password : req.body.password, password_confirmation : req.body.password_confirmation, agreetoterms: req.body.agreetoterms } 

然后将该variables传递给视图

 res.render('register.html', { pageErrors: [{msg: dbErrorMessage }], inputData: inputData }); 

那么在你看来

 value="<%= inputData.userName %>" 

如果你使用玉并从npm形成Validator,那么最好的部分就是你可以在jade中使用if语句,然后你只需检查是否有错误,然后用res.render来发送对象。 看到这个

 if(errors){ res.render('register',{ errors : errors, name : name, email : email, username : username, password : password, password2 : password2 }); 

而在玉器里,你这样做

 input.form-control(name='name',type='text',placeholder='Enter Name',value = (errors ? '#{name}':'')) 

所以如果有错误,值将设置为名称的variables,当我们发回时会渲染

我想你也可以在Angular2 / Angular.js中完成

检查http://www.quietless.com/kitchen/building-a-login-system-in-node-js-and-mongodb/

在register.html做这个

  var data = {}; data.user = $('#user-input').val(); data.email = $('#email-input').val(); data.pass = $('#pass-input').val(); $.ajax({ url: '/signup' , type: 'POST' , data: JSON.stringify(data) , contentType: 'application/json' , dataType: 'html' }) .done(function(data) { if (data == 'ok') { $('#content').html('You are registered!'); } else $('#account-form-container').append('<br>error:' + data); }); 

可能会出现以下错误:无法开机自检/

在这种情况下,上面的链接教程的作者使用lib $ .ajaxForm

你也可以使用https://github.com/felixge/node-formidable

或$('#myform')。submit()replace为$('#submit-a-link')。click()