smile
smile

Reputation: 102

can't set headers after they sent in node js

I am using nodejs with express framework and my db is postgres db.I had 2 issues on that.First one, when I perform login verification using select query it executes correctly suppose if the user is not in db the query terminates How i can use if else here without using query on end.here i gave my else part to query on block.And then second, I am using 2 times res.send so I got an error how can i render the page and send data to ajax call.

script.
  $(document).ready
    console.log('bbbbbbbb');
    $('#loginform').submit(function(e) {
    console.log('submit called');
    var data = {};
    data.email = $('#username').val();
    data.password = $('#password').val();
    JSON.stringify(data);
    console.log(data);


    $.ajax({
      url: "/login",
      type: "POST",
      dataType: 'json',
      data: JSON.stringify({ "objectData": data}),
      contentType: "application/json",

      success: function(data) {
        alert('SUCCESS":'+JSON.stringify(data));
        var successVar = data;
        alert(successVar.data);
        if(successVar.data == "Invalid username And Password"){
        location.href='/';
        }
        if(successVar.data == "Login successfully"){
          location.href='http://localhost:3000/landing';
        }


      },

    });
  return false;
  });
My call 


     exports.login = function(req, res) {
      var resultObject = (req.body.objectData);
      var user = client.query("SELECT * FROM login where email_id='" + resultObject.email + "'            AND password='" + resultObject.password + "'");

     user.on("row", function(row ,err) {
     console.log(row);

     var register_id = row.login_id;
     console.log(register_id);

     res.send({data:"Login successfully"});
     res.render('landing.jade');
     });

     user.on("end", function(result) {
     res.send({data:"Invalid username And Password"});

     });

     };

Upvotes: 0

Views: 247

Answers (2)

Rajiv S
Rajiv S

Reputation: 28

enjoy this code

exports.login = function(req, res) {
    console.log("enter the login999999999");
    console.log(req.body); 
  var resultObject = (req.body.objectData);

 client.query("SELECT * FROM login where email_id='" + resultObject.email + "' AND password='" + resultObject.password + "'", function(err, result) {
    console.log("Row count: %d",result.rows.length);  // n
    if(result.rows.length>0){
        console.log('successfully');
        res.send({data:"Login successfully"});
    } else {
        console.log('not successfully');
        res.send({data:"Invalid username And Password"});
    }
});
 };

Upvotes: 1

kaxi1993
kaxi1993

Reputation: 4710

it's simple:

 res.render('landing',{'data':data})

Upvotes: 0

Related Questions