Wednesday, 7 June 2017

Using session in ejs

I am a newbie in node and express. I want to use cookies / session to notify my ejs once my registration is successful. I dont know which one is a better option, please suggest. Also help me with their usage.

Below are snippets of my controller ( server-side js ) and register-user ( client side js ).

registerController.js

app.post('/register',urlencodedParser,function(req,res){
  session=req.session;
  Users(req.body).save(function(err,data){
    if(err) throw err;
    console.log(" back from ajax with data :::; " + data);
    req.session.user='sasdad';      
    res.status(200).send('User saved successfully');
  });
});

register-user.js

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

   return false;
});  

EJS

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



via Saurabh Jhunjhunwala

No comments:

Post a Comment