2012-11-28 22 views
8

Tôi đang làm việc trên một mẫu đăng ký thực sự cơ bản trong Node.js (với Express), và tôi đang cố gắng tìm cách dễ nhất để cung cấp xác nhận biểu mẫu cơ bản. Tôi đã đi với "Express-Validator", mà dường như làm một công việc tốt. Tuy nhiên, mục tiêu của tôi là chỉ hiển thị bất kỳ thông báo xác thực nào được yêu cầu và để để các giá trị được nhập bởi người dùng một mình.Node.js (Express) Biểu mẫu Clears về thông tin

Dường như thông tin yêu cầu không được đưa trở lại vào vị trí res.render mà tôi đoán là hợp lý. Tuy nhiên, tôi đã nhìn ở khắp mọi nơi tôi có thể nghĩ đến và tôi không thể tìm thấy bất kỳ tài liệu tham khảo nào thảo luận về cách giữ cho các trường biểu mẫu được điền sau khi hiển thị thông báo lỗi.

Dưới đây là một đoạn nhỏ mô tả cách tiếp cận của tôi:

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 }); 
      } 
+0

Đây là những gì mọi người có ý nghĩa khi họ nói rằng "web là không quốc tịch". Bạn cần phải điền lại các giá trị của mình theo cách thủ công sau mỗi yêu cầu. –

+1

Vâng, tôi nhận ra rằng nó sẽ yêu cầu sự can thiệp từ phía máy chủ để trả lại các giá trị, nhưng tôi hy vọng rằng express có thứ gì đó (hoặc phần bổ trợ trung gian) có thể làm điều này cho chúng ta. Tôi sẽ chỉ đi tuyến gửi biểu mẫu AJAX. Dù sao, nó sẽ làm cho trải nghiệm người dùng tốt hơn. – creativename

Trả lời

10

Thật không may, bạn phải phục hồi lại các hình thức bằng tay. Nếu bạn nhận được bất kỳ lỗi trang nào, bạn sẽ trả lại giá trị biểu mẫu cho chế độ xem.

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

Và theo quan điểm của bạn, bạn sẽ thực hiện kiểm tra đơn giản để xem liệu có lỗi nào không và sửa lại cho phù hợp. Bạn sẽ phải theo dõi những lỗi nào được tạo ra cho mỗi trường biểu mẫu.

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

Một cách phổ biến khác là gửi biểu mẫu của bạn qua ajax tới máy chủ và thực hiện tất cả các xác thực của bạn. Nếu có lỗi, dữ liệu biểu mẫu đã nhập vẫn còn và bạn sẽ hiển thị lỗi, nếu không sẽ chuyển hướng sau khi đăng nhập thành công. Dưới đây là ví dụ về cách gửi biểu mẫu bằng 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; 
}); 
+1

+1. Tùy thuộc vào độ phức tạp của ứng dụng, có thể dễ dàng gửi biểu mẫu qua Ajax và trả về các thông báo lỗi qua JSON (và cập nhật trang tương ứng với JavaScript). –

+0

Cảm ơn, tôi nghĩ đó là cách tôi sẽ phải đi, sau đó. Tôi sẽ chỉ gửi biểu mẫu dưới dạng cuộc gọi AJAX và đi từ đó.Tôi nghĩ rằng nó có thể được "dễ dàng hơn" để làm bài viết đầy đủ trở lại, nhưng đó là trên giả định rằng thể hiện bằng cách nào đó có thể giúp đỡ trong việc trả lại giá trị đầu vào. Tôi đoán đó là những gì tôi nhận được từ .NET! – creativename

-1

séc http://www.quietless.com/kitchen/building-a-login-system-in-node-js-and-mongodb/

trên register.html làm này

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

có thể có lỗi như: KHÔNG THỂ POST/

trong trường hợp này là tác giả của hướng dẫn về sử dụng diễn đàn lib $ .ajaxForm

bạn cũng có thể sử dụng https://github.com/felixge/node-formidable

hoặc $ ('# MyForm'). Submit() thay thế để $ ('# nộp-một-link'). Click()

5

Có một cách dễ dàng là bạn đang sử dụng

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

bạn có thể sử dụng req.body

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

Và tôi không chắc chắn ngôn ngữ khuôn mẫu bạn đang sử dụng nhưng bạn có thể làm điều gì đó như ..

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

Điều này sau đó cung cấp lại đầu vào tốt nếu ok hoặc đầu vào xấu nếu cần chỉnh sửa.

+0

Cảm ơn bạn, tôi nghĩ rằng đây thực sự là cách chính xác để sử dụng "pageErrors" mà expressValidator tạo ra. Tôi nên làm một sự kết hợp của xác nhận AJAX và sau đó sử dụng này như là dự phòng trong trường hợp JavaScript bị vô hiệu hóa. – creativename

0

thiết lập một biến cho tất cả các đầu vào, ví dụ

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 
} 

và sau đó vượt qua biến mà đến xem

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

sau đó theo quan điểm của bạn

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

Bạn có thể nhận việc này được thực hiện bằng cách sử dụng connect-flash

Dưới đây là các đoạn mã trong các tệp khác nhau để lấy các giá trị do người dùng nhập vào trong biểu mẫu khi xác thực không thành công khi đăng ký với hộ chiếu.

Chạy lệnh dưới đây để thêm gói mới vào 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 (Xin vui lòng tập trung vào hình thức tải dữ liệu vào 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); 
      }); 
    }); 
})); 

tuyến/index.js (Xin vui lòng tập trung vào dữ liệu mẫu trong flash nạp lại vào một biến)

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 (Xin vui lòng tập trung vào các giá trị trong các yếu tố đầu vào)

<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> 

Hy vọng điều này sẽ hữu ích.

0

nếu bạn đang sử dụng ngọc bích và biểu mẫu Validator từ npm, phần tốt nhất là bạn có thể một tuyên bố nếu trong ngọc và sau đó bạn chỉ cần kiểm tra nếu lỗi sau đó với res.render chúng tôi gửi các đối tượng cũng có. Xem này

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

Và trong ngọc bích bạn làm điều này

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

vì vậy nếu có sai sót giá trị sẽ thiết lập để biến tên đó sẽ trả lại khi chúng tôi gửi lại

Tôi nghĩ bạn cũng có thể được thực hiện trong Angular2/Angular.js

Các vấn đề liên quan