0

I am new in Node and trying to develop some initial apps. I am currently inserting record into database(MySQL) through Node. My post method is like

router.post('/add',function(req,res){
    connection.connect();
    var firstName = req.body.FirstName;
    var lastName = req.body.LastName;
    students.push({
        //id: studentList.length+1,
        FirstName: firstName,
        LastName: lastName
    });
    var post  = {FirstName: firstName, LastName: lastName};
    connection.query('INSERT INTO tblstudent VALUES ? ', post,function(err,result){
        if (err) {
                res.send("There was a problem adding the information to the database.");
            }
    });
    res.redirect('/');
    connection.end();
});

where Id is another column but auto incremented, so I trying to insert record. I'm having the following error.

enter image description here

Nomi Ali
  • 2,165
  • 3
  • 27
  • 48
  • Please look into this: http://stackoverflow.com/questions/7042340/node-js-error-cant-set-headers-after-they-are-sent – Dhruv Sep 08 '15 at 09:37

1 Answers1

1

Error: Can't set headers after they are sent

This error means that headers where already set but one more is trying to be set up.

In your case, you have called res.redirect(), making the response finished. Then your code threw an error because query has failed, and you`ve tried to set a response: "res.send("There was a problem adding the information to the database.");".

In order to fix the problem you should move res.redirect('/'); in to callback function of the query.

connection.query('INSERT INTO tblstudent VALUES ? ', post,function(err,result){
    if (err) {
            res.send("There was a problem adding the information to the database.");
        } else {
            res.redirect('/');
        }
});
Alexandr Lazarev
  • 12,554
  • 4
  • 38
  • 47