如何在成功获取数据后停止 API GET 请求

How to stop API GET request once data is fetched successfully

我的问题与 MEAN 堆栈密切相关。我想获取存储在我的 MongoDB 数据库中的文档总数。我的快递服务器工作正常,但在邮递员上我仍然可以看到它仍在发出请求,即使我在控制台上得到了正确的计数:

这是我的代码:

api.js

const uri = 'mongodb://tanzee.......ue&w=majority'
const { MongoClient } = require("mongodb");
const client = new MongoClient(uri);

router.get('/totalmovies', function(req, res) {
    run().catch(console.dir);
});

async function run() {
    try {
      await client.connect();
      const database = client.db("mycollection");
      const movies = database.collection("movies");
      const estimate = await movies.estimatedDocumentCount();
      console.log(`Estimated number of documents in the movies collection: ${estimate}`);
    } finally {
      await client.close();
    }
}

我从mongodb的官方文档中得到了帮助:https://docs.mongodb.com/drivers/node/usage-examples/count/

输出:

(node:15511) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.

Estimated number of documents in the movies collection: 80

我是这个堆栈的新手。获取输出后,我的代码应立即停止 GET 调用。请指出我的错误。

您的代码是正确的,由于您没有发送任何响应,请求处于待处理状态,这就是请求者仍在等待接收响应的原因。一个简单的解决方法是将数据发送回请求者。


router.get('/totalmovies', async function(req, res) {
    const result = await run();
   // check how are you getting result when it is a success/failure
   // apply condition same in the below if/else 
   // it just for reference, it might be correct though
    if (result > 0) {
       res.status(200).send(result); 
    } else {
       res.status(404).send({'No Data in DB'});
    }     
});

(node:15511) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.

要让它起作用:

const client = new MongoClient(uri, { useNewUrlParser: true }) 

不要为每个请求关闭并重建连接:

async function run() {
    try {
      await client.connect();
      const database = client.db("mycollection");
      const movies = database.collection("movies");
      const estimate = await movies.estimatedDocumentCount();
      console.log(`Estimated number of documents in the movies collection: ${estimate}`);
      return estimate;
    } catch (e){
        console.error('Error in fetching the data from DB')
    }
}