1

I am a newbie in node and express. I am working on an app that has a login module. I am able to register a user but am facing some issues while trying to log in a user.

Please find my code below and suggest:

Logincontroller.js

app.post('/testAction',urlencodedParser,function(req,res){

    var usrnm = req.body.username;
    console.log(" usrnm ::: " + usrnm);
    var passwd = req.body.password;
    console.log(" passwd ::: " + passwd);
    Users.findOne({username:"tstusr1"},function(err,data){ // Users is my schema name
        if(err) throw err;
        console.log(" back from ajax with data in login controller :::; " + data);
        res.json(data);
    });
    console.log("inside index2 post");
});

my Login-user.js is

$(document).ready(function(){

      var items = $('form');
      var user ={username: $('[name=username]', items).val()};     
      console.log('user  ' + JSON.stringify(user));

  $('form').on('submit', function(){
      console.log("inside submit login");
      $.ajax({
          type: 'POST',
          url: '/testAction',
          data: user,
          success: function(data, textStatus, jqXHR){
            var resp = JSON.parse(JSON.stringify(jqXHR));
            if(resp["status"]==200){
                console.log("status == 200");
                window.location.href = '/';
            }  
              return data;
          },
          error:function (jqXHR, textStatus, errorThrown) {

              console.log('error  ' + JSON.stringify(user));
              console.log("resp1 :::::: " + JSON.stringify(jqXHR));
              var resp = JSON.parse(JSON.stringify(jqXHR));
              console.log("resp :::::: " + resp);
          }
        });
         return false;
  });  
});

And my ejs file is

<form action="/testAction">
    <label for="username"> Username </label>
    <input type="text" for="username" name="username" />
    <label for="password"> Password </label>
    <input type="password" for="password" name="password" />
    <button type="submit">Log In</button> 
</form>

My issue is I am not able to fetch the values of username and password to the client side js as well as backend server side js.

Please assist

Saurabh Jhunjhunwala
  • 2,832
  • 3
  • 29
  • 57
  • Do you get an error at any point? You also probably want a `event.preventDefault()` in your form handler. Also are you updating `user` at all? – noahnu Jun 05 '17 at 19:07
  • As of now, there is no requirement like that, but thanks for the suggestion, will keep an eye on that – Saurabh Jhunjhunwala Jun 05 '17 at 19:10
  • Your issue is not clear enough. Do you get an error message? What do you mean "not able to fetch the values ... to the client ... as well as ... server"? The values are already on the client. Did you correct the issues I posted in my answer below? You're not even sending the latest username, only empty value when the page loads. – noahnu Jun 05 '17 at 19:33

2 Answers2

0

From the code posted, you don't seem to be updating user at all. Neither are you actually including the password in the request's data parameter.

$('form').on('submit', function(e) {
  e.preventDefault();
  $.post('/testAction', {
    username: $('[name=username]', $(this)).val(),
    password: ...
  });
});

If you want a simpler way to pass all the fields from your form:

$('form').on('submit', function(e) {
  e.preventDefault();
  $.post('/testAction', (
    $(this).serializeArray().reduce((o, i) => {
      o[i.name] = i.value;
      return o;
    }, {})
  ));
});

See How can I get form data with JavaScript/jQuery?

noahnu
  • 3,479
  • 2
  • 18
  • 40
0

Found the solution:

Logincontroller.js

app.post('/testAction',urlencodedParser,function(req,res){

    var reqData = JSON.parse(JSON.stringify(req.body));
    console.log(" reqData username :::::::: " + reqData['username']);

    console.log(" reqData password :::::::: " + reqData['password']);

    Users.findOne({username:reqData['username']},function(err,data){
        if(err) throw err;
        console.log(" back from ajax with data in login controller :::; " + data);
        res.json(data);     
});

Login-user.js

$(document).ready(function(){   

  $('form').on('submit', function(){
      console.log("inside submit login");

      var items = $('form');
      var user ={
              username: $('[name=username]', items).val(),
              password: $('[name=password]', items).val()
           }; 

      $.ajax({
          type: 'POST',
          url: '/testAction',
          data: user,
          success: function(data, textStatus, jqXHR){
            var resp = JSON.parse(JSON.stringify(jqXHR));
            console.log(" resp :::::: " + resp);
            if(resp["status"]==200){
                console.log("status == 200");
                var respData =JSON.parse(JSON.stringify(data));
                var enteredPassword = JSON.parse(JSON.stringify(user));
                console.log(" respData password :::::: " + respData.password);
                console.log(" enteredPassword password :::::: " + enteredPassword.password);

                if(enteredPassword.password==respData.password){
                    console.log("success Matched");
                }else {
                    console.log("unsuccessful not-Matched");
                }

            }  
              return data;
          },
          error:function (jqXHR, textStatus, errorThrown) {

              console.log('error  ' + JSON.stringify(user));
              console.log("resp1 :::::: " + JSON.stringify(jqXHR));
              var resp = JSON.parse(JSON.stringify(jqXHR));
              console.log("resp :::::: " + resp);
          }
        });
         return false;
  });  
});

ejs File :

<form action="/testAction">
    <label for="username"> Username </label>
    <input type="text" for="username" name="username"/>
    <label for="password"> Password </label>
    <input type="password" for="password" name="password" />

    <button type="submit">Log In</button> 
</form>
Saurabh Jhunjhunwala
  • 2,832
  • 3
  • 29
  • 57