我正在嘗試在提交表單後將頁面重定向到我的主頁(使用路徑'/ 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')
以便它不返回此錯誤。
任何幫助,非常感謝!先謝謝你!