【问题标题】:NodeJS HTTPResponse from MongoDB来自 MongoDB 的 NodeJS HTTPResponse
【发布时间】:2018-11-28 21:56:14
【问题描述】:

我有一个正在等待 HTTPREQUESTS 的 NODEJS 服务器。根据请求,它从 MongoDB 获取一些数据并将其作为响应发送回。 JavaScript 是一种同步语言,因此响应总是在从数据库获取数据之前发送。这是我去 localhost:8080 时编写的测试代码,如果我刷新我得到实体,我什么也得不到。就像我说的我知道为什么,我的问题是我不知道如何让服务器等待响应,直到数据库回答。我需要一个事件或其他东西,但我不知道我应该如何实现它......

var http = require('http');
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
var requrl= "localhost:2442"
var testResult = "";



http.createServer(function(requrl,res){      
    var MongoClient = require('mongodb').MongoClient;
    var url = "mongodb://localhost:27017/"; 
        MongoClient.connect(url,  { useNewUrlParser: true },function(err, db) {
        if (err) throw err;
    var dbo = db.db("mydb");   
            dbo.collection("UserInformations").find({name:"a"},{projection: {_id:0}}).toArray(function(errorinfind,result){
            if(errorinfind)throw errorinfind;  
            db.close();
            testResult = result[0].name;
    }); 
});
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(testResult.toString());
    res.end();   
}).listen(8080);

【问题讨论】:

  • 您需要在数据库查询的回调中执行 response.write

标签: node.js mongodb http


【解决方案1】:

您可以使用async/await。如下:

http.createServer(async function(requrl,res){      
    var MongoClient = require('mongodb').MongoClient;
    var url = "mongodb://localhost:27017/"; 
        var db = await MongoClient.connect(url,  { useNewUrlParser: true })       
        var dbo = db.db("mydb");   
        var resualt = (await dbo.collection("UserInformations").find({name:"a"},{projection: {_id:0}})).toArray();  
        db.close();
        testResult = result[0].name;


        res.writeHead(200, {'Content-Type': 'text/html'});
        res.write(testResult.toString());
        res.end();   
        }).listen(8080);

如果你想处理错误,你可以用try/catch包围它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    相关资源
    最近更新 更多