AJAX > MongoDB 查询只工作了五次,然后服务器停止处理请求,我无法刷新页面

AJAX > MongoDB query only works five times, then server stops handling requests, and I can't refresh the page

我正在构建一个 React / Express / MongoDB 应用程序。我正在尝试进行 returns 结果为您键入的实时搜索。服务器上的数据库调用只工作了五次,然后就停止了。然后我无法刷新浏览器,所以我认为此时服务器停止处理请求。我是否阻止了 Node 的事件循环?

当我停止服务器时,所有未答复的响应都显示在浏览器控制台中:

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

这是我的 AJAX 电话。注意:这被限制为以 800 毫秒的最大频率调用。

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

这里是 express js 代码:

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

为什么它只能工作五次,即使我在搜索字段中按下每个字符之前等待几秒钟?

看来问题是您的服务器上的正常路径没有发送任何响应。看看这是否有效。如果这不能解决问题,请包含定义 db 参数并将其作为参数传递给 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);
    })
}