我试图在提交表单后将页面重定向到我的主页(使用路由“/search”)。在我的 submit.html
文件中,我有一个表单,当按下提交按钮时,表单中的数据通过“/submit”post 方法提交。在我的 index.js
文件中,我有一个用于“/submit”的 get 和 post 函数,这样我就可以访问 MongaDB 和集合。以下是函数:
//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:sillydoo@ds059195.mlab.com: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');
并返回错误:错误:发送后无法设置 header 。经过研究,我意识到这个错误是因为我处于 Body 或 Finished 状态。但是,我无法弄清楚我需要写什么而不是将页面重定向到我的“/search”路由或我可以写 res.redirect('/search')
的地方,这样它就不会'返回这个错误。
非常感谢任何帮助!提前致谢!
最佳答案
Check this answer , 你不能发送多个响应。
在这里,如果不需要,请删除res.send
关于javascript - 如何使用 Node JS 重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36199674/