2

I am building a React / Express / MongoDB app. I am trying to make a live search that returns results as you type. The DB call on the server only works five times, and then stops. Then I can't refresh the browser, so I think the server at that point stops handling requests. Did I block Node's event loop?

When I stop the server, all the unanswered responses show up in the browser console:

POST http://localhost:3000/action/searchTextIndex net::ERR_EMPTY_RESPONSE POST http://localhost:3000/action/searchTextIndex net::ERR_EMPTY_RESPONSE POST http://localhost:3000/action/searchTextIndex net::ERR_EMPTY_RESPONSE

Here is my AJAX call. NOTE: this is throttled to call at an 800ms max frequency.

    search(query, dbCollection) {
        axios.post('/action/searchTextIndex', {
            dbCollection,
            query
        })
        .then(response => {
            console.log(response);
        })
        .catch(err => console.log(err))
    }

And here is the express js code:

    const searchTextIndex = (req, res, db) => {
        const { query, collection } = req.body;

        db.collection(collection).find(
            { $text: { $search: query } }
        )
        .project({ score: { $meta: 'textScore' } })
        .sort({ score: { $meta: 'textScore' } })
        .toArray((err, result) => {
            if (err) {
               console.log(err);
               res.send({ type: 'server_error' });
               return;
             }

             console.log(result);
             return;
        })
    }

Why would it only work five times, even if I wait a few seconds before pressing each character in the search field?

nth-chile
  • 616
  • 1
  • 7
  • 20

1 Answers1

1

It looks like the problem is that no response is sent for the happy path on your server. See if this works. If this doesn't fix it, include the code where the db parameter is defined and passed as an argument to searchTextIndex.

const searchTextIndex = (req, res, db) => {
    const { query, collection } = req.body;

    db.collection(collection).find(
        { $text: { $search: query } }
    )
    .project({ score: { $meta: 'textScore' } })
    .sort({ score: { $meta: 'textScore' } })
    .toArray((err, result) => {
        if (err) {
           console.log(err);
           res.send({ type: 'server_error' });
           return;
         }

         console.log(result);
         
         // need to be sure you send the response
         return res.json(result);
    })
}
webprojohn
  • 958
  • 7
  • 14
  • Oh wow! It looks like the request gets blocked, or the server becomes unresponsive, if it doesn't respond 5 times? That's strange / I don't understand ... but it works. – nth-chile Sep 24 '18 at 00:25