user3692825
user3692825

Reputation: 126

How to redirect using Node JS?

I am trying to redirect a page to my home page (with the route '/search') after submitting a form. In my submit.html file, I have a form and when the submit button is pressed the data in the form is submitted via the '/submit' post method. In my index.js file, I have a get and post function for '/submit' so that I can access the MongaDB and collection. Here are the functions:

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

});

At the end of the function I tried to call res.redirect('/search'); and it returned the error: Error: Can't set headers after they are sent. After doing research I realized this error is occurring because I am in the Body or Finished state. However, I can't figure out what I need to write instead to redirect the page to my '/search' route or where I can write res.redirect('/search') so that it doesn't return this error.

Any help is greatly appreciated! Thank you in advance!

Upvotes: 1

Views: 117

Answers (3)

scarecrow
scarecrow

Reputation: 1615

Check this answer, You can't send multiple response.

Here, remove res.send if it's not necessary

Upvotes: 2

Vladimir G.
Vladimir G.

Reputation: 885

Replace res.send(''); in the insertDocumentcallback with res.redirect('/search');. If you don't want to wait while DB stuff completed than just remove res.send('');

Upvotes: 1

Jeff P Chacko
Jeff P Chacko

Reputation: 5018

this is because you are sending response twice. one at

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

and one at the bottom as

res.redirect('/search');  

Remove res.send and you'll be fine. always make sure that you only send response once.

Upvotes: 1

Related Questions