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

1

1 Answer 1

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('/');
        }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.