2015-09-08 80 views
0

我是Node中的新手,嘗試開發一些初始應用程序。我目前通過Node將記錄插入到數據庫(MySQL)中。我的文章方法就像通過節點插入記錄到MySQL數據庫時出錯

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(); 
}); 

其中Id是另一列,但自動遞增,所以我試圖插入記錄。我有以下錯誤。

enter image description here

+0

請看看這個: http://stackoverflow.com/questions/7042340/node-js-error-cant-set-headers-after-they-are-sent – Dhruv

回答

1

Error: Can't set headers after they are sent

此錯誤意味着在已經設置,但多了一個試圖頭進行設置。

就你的情況而言,你調用了res.redirect(),使得響應結束。然後你的代碼拋出一個錯誤,因爲查詢失敗了,你試圖設置一個響應: 「res.send(」在將信息添加到數據庫時出現問題。「);」。

爲了解決這個問題,您應該將res.redirect('/');移動到查詢的回調函數中。

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('/'); 
     } 
}); 
相關問題