如何使用Node JS重定向?

时间:2016-03-24 12:00:26

标签: javascript node.js forms redirect express

我正在尝试在提交表单后将网页重定向到我的主页(使用路线' / search')。在我的submit.html文件中,我有一个表单,当按下提交按钮时,表单中的数据将通过' / submit'提交。发布方法。在我的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');并返回错误:错误:发送后无法设置标头。在做了研究后,我意识到这个错误正在发生,因为我处于身体或完成状态。但是,我无法弄清楚我需要写什么,而是将页面重定向到我的' / search'路线或我可以写res.redirect('/search')的地方,以便它不会返回此错误。

非常感谢任何帮助!提前谢谢!

3 个答案:

答案 0 :(得分:2)

Check this answer,您无法发送多个回复。

此处,如果没有必要,请删除res.send

答案 1 :(得分: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,你会没事的。始终确保您只发送一次响应。

答案 2 :(得分:1)

res.send('');回调中的insertDocument替换为res.redirect('/search');。如果您不想等待数据库填充完成而不是仅删除res.send('');