0

I am currently using Node.js, Express.js, and MongoDB to create a basic REST API. I am trying to redirect to another page after executing a query but my console is throwing the error in the title. Here is my code:

    app.post('/', (req, res) => {
  MongoClient.connect(process.env.DB_CONNECTION, { useUnifiedTopology: true, useNewUrlParser: true }, function (err, db) {
    if (err) throw err;
    const dbo = db.db("mydb");
    const messageTable = dbo.collection("messages");
    let myobj = { message: req.body.message };
    console.log(myobj)
    messageTable.insertOne(myobj, function (err, res) {
      if (err) throw err;
      console.log("1 document inserted");
      db.close();
    });
  });
  //Get message
  MongoClient.connect(process.env.DB_CONNECTION, { useUnifiedTopology: true, useNewUrlParser: true }, function (err, db) {
    const messageTable = db.db('mydb').collection('messages');

    var myPromise = () => {
      return new Promise((resolve, reject) => {
        messageTable.aggregate(
          [{ $sample: { size: 1 } }]
        ).toArray((err, data) => {
          err
            ? reject(err)
            : resolve(data[0]);
        });
      });
    }
    //Step 2: async promise handler
    var callMyPromise = async () => {
      var result = await (myPromise());
      //anything here is executed after result is resolved
      return result;
    };

    //Step 3: make the call
    callMyPromise().then(function (result) {
      db.close();
      res.json(result);
      res.redirect('/');
      });

    });

  });  //end mongo client

The code only throws errors when I include the res.redirect('/');.

Also I do not know if this has anything to do with it but here is my get request:

    app.get('/', (req, res) => {
  fs.readFile('./views/home.html', function (err, data) {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.write(data);
    res.end();
  });
TDonnally
  • 67
  • 10
  • Does this answer your question? [res.send(), then res.redirect()](https://stackoverflow.com/questions/21439526/res-send-then-res-redirect) – Shlang Mar 07 '20 at 22:36
  • @Shlang It does not. Even if I check the status code I get the same error. I edited my initial response to include my get request since maybe that has something to do with it. – TDonnally Mar 07 '20 at 22:43
  • 1
    You're sending a response in your Step 3: `res.json(result)`. Then, you're trying to send another response again: `res.redirect('/')`. What's the expected behavior here? – shkaper Mar 07 '20 at 23:04
  • @shkaper I want to get the document from my database and then redirect to the home page that has a form. I want to be able to then use display the result data along with the form and allow the user to submit more data. How can I do both responses? – TDonnally Mar 07 '20 at 23:09
  • @shkaper how can I ensure res.json(result) runs before I redirect? – TDonnally Mar 07 '20 at 23:10
  • `res.json` and `res.redirect` are both methods that send their respective headers, bodies, ending the responses after that. You're asking how to send 2 different responses to a single request - it's not possible. If you need to redirect the user while passing some context (a result of some kind) - take a look here: [How do I redirect in expressjs while passing some context?](https://stackoverflow.com/q/19035373/5045563) – shkaper Mar 07 '20 at 23:25
  • We need to see the containing context for your first code block. Is this inside an `app.get()`? If so, please show that. You are attempting to send two responses to the same request with both `res.json()` and `res.redirect()`. You can't do that. You only get to send ONE response. Why are you trying to send two responses? What are you trying to accomplish with that? – jfriend00 Mar 07 '20 at 23:37
  • @jfriend00 I edited my code to show context. The reason I want to redirect is so my app loops. It sends the user back to the form so they can enter more data. – TDonnally Mar 07 '20 at 23:42
  • Then, don't use `res.json()` at all if nobody is paying attention to that at the end. Put the `res.redirect()` in place of that and remove the other `res.redirect()`. FYI, it's very odd that you're connecting to your database twice in the same function. Can't you just use one connection for two separate DB operations? You are also missing a lot of proper error handling. – jfriend00 Mar 07 '20 at 23:44
  • Also, the `callMyPromise()` function has zero purpose. You can remove it. I'd also recommend using the promise interface built-into your database rather than wrapping your own promises around the db operations. – jfriend00 Mar 07 '20 at 23:46

0 Answers0