0

I am using nodeJS and express to create a simple log in form where user need to put their email and password to log in. For example, in client side:

  form(action='/login', method='post')
      .form-group
        label Email
        input.form-control(type='text', name='email')
        span#message
      .form-group
        label Password
        input.form-control(type='password', name='password')
      button.btn.btn-warning.btn-lg(type='submit') Login

In server side:

router.get('/', function(req, res, next) {
res.render('index', { title: 'Login' });

// process the login form
router.post('/login', function(req, res){
    if(req.body.email && req.body.password == 'pass123') {
        res.redirect('/myHomePage);
    }else {
        res.redirect('/');
    }
 });

My question is, how can I check if user is enter the valid email and valid password (which declared in server-side (pass123)). How can I have a popup/ or a message on client side to tell user that they input the wrong username/password.

I am not using any database at the moment.

kaqqao
  • 12,984
  • 10
  • 64
  • 118
Tenz
  • 535
  • 2
  • 7
  • 27

1 Answers1

1

The following code is not tested, but it should lead you in the right direction.

With reloading the page

Look at this answer. So you basically redirect to your login page (or whatever page you want to redirect to) while appending the get parameters, so i.e.

router.post('/login', function(req, res){
    if(req.body.email && req.body.password == 'pass123') {
        res.redirect('/myHomePage);
    }else {
        res.redirect('/'+ '?somevar=value&...');
    }
});

and then handle the get 'like

router.get('/', function(req, res, next) {
 res.render('index', { title: 'Login', someMessage: req.query.somevar });
});

Without reloading the page

If you do an ajax request i.e. with $.ajax, you could handle your post routine like

router.post('/login', function(req, res){
if(//password not valid) {
    res.send(JSON.stringify({ userValid: 0 }));
}
else
    res.send(JSON.stringify({ userValid: 1 }));

});

where the client would handle it something like

//some click event or whatever you do to start logging in
$.ajax({
  url: "/login",
  method: "post"
}).done(function(data) {
  if(data.userValid) {
  //redirect to home page
  }
  else
     //insert some message into your html 
});

Edit 1:

Assuming that after the user has inserted his credentials, he has to click a button, a link etc. to start the login process and further assuming that you are using jQuery, you can then just do

$(<selector of button, link etc>).click(function(){
    $.ajax(....);
});

Note that when using i.e. a submit button inside a form, you have to prevent the default action of the submit button, specifically

$(<selector of button, link etc>).click(function(e){
    $.ajax(....);
    e.preventDefault();
});

Some applies for a link i.e.

Community
  • 1
  • 1
VGD
  • 436
  • 1
  • 5
  • 25