2016-03-24 42 views
1

我正在嘗試在提交表單後將頁面重定向到我的主頁(使用路徑'/ search')。在我的submit.html文件中,我有一個表單,當按下提交按鈕時,表單中的數據通過'/ submit'提交方法提交。在我的index.js文件中,我有'/ submit'的get和post函數,以便我可以訪問MongaDB和集合。下面是功能:如何使用Node JS重定向?

//getting info from the database 
router.get('/submit', function(req, res) { //RETURN JSON OF INTINERARIES 
    var db = req.db; //Creates a variable called db, which equals the database called db (db holds the collegelist collection) 
    var collection = db.get('collegelist'); //Creates a variable called collection which accesses the collection called collegelist 
}); 

router.post('/submit', function(req, res){ 
    var url = 'mongodb://localhost:27017/maptest'; //IDENTIFIES THE MONGO DB 
    //var url = 'mongodb://dbuser2:[email protected]:59195/heroku_vmz14q76'; 

    function insertDocument(db, record, callback) { //this creates a function to insert data into collegelist 
    db.collection('collegelist').insertOne(record, 
    function(err, result) { 

     assert.equal(err, null); //error must equal null 
     console.log("Function for inserting a document."); 

     callback(result); //calling back on the result? 
    }); 
    }; 

    //this grabs the data from the form using ids and assigns it to the parameters in the collegelist database 
    req.body['name'] = req.body.name; //INSERTING THE EMAIL INTO THE FIELDS THAT ARE COLLECTED 

    //connects to the mongodatabase (the variable url equals the database -- either mongolab or local) 
    MongoClient.connect(url, function(err, db) { //MONGO CLIENT IS CONNECTING TO THE URL -- TWO POSSIBLE OUTCOMES: ERROR OR THE DB 
    assert.equal(null, err); //ERROR MUST BE NULL FOR THE PROGRAM TO CONTINUE 
    insertDocument(db, req.body, function(result) { //this calls on the insert document function I just created 
     //RECORD IS CALLED REQ.BODY IN THE LINE ABOVE 
     db.close(); //CLOSE CONNECTION WITH THE DB 
     console.log("DB Result :", result); //LOGGING IT! 
     //ALL THE CODE IN THIS ANNONYMOUS FUNCTION IS THE CALLBACK IN THE INSERTDOCUMENT FUNCTION 
     res.send(''); 
    }); 
}) 

res.redirect('/search'); 
//res.render('search', { username: req.user.givenName }); 

}); 

在函數結束時,我試着撥打res.redirect('/search');和它返回的錯誤:錯誤:發送之後無法設置頭。在做研究之後,我意識到這個錯誤正在發生,因爲我處於Body或Finished狀態。然而,我不知道我需要寫什麼,而是將頁面重定向到我的'/ search'路徑,或者我可以寫res.redirect('/search')以便它不返回此錯誤。

任何幫助,非常感謝!先謝謝你!

回答

1

res.redirect('/search');替換res.send('');中的insertDocument回調。如果您不想等待數據庫內容完成而不是僅僅刪除res.send('');

2

Check this answer,您無法發送多個響應。

這裏,除去res.send如果它沒有必要

1

這是因爲您要發送的響應兩次。 一個在

console.log("DB Result :", result); //LOGGING IT! 
    //ALL THE CODE IN THIS ANNONYMOUS FUNCTION IS THE CALLBACK IN THE INSERTDOCUMENT FUNCTION 
    res.send(''); 

,一個在底部,

res.redirect('/search'); 

刪除res.send,你會沒事的。始終確保您只發送一次回覆。