Sunday 27 September 2020

Problem with res.send(), need help!

I am a complete newbie in nodejs. Here is the following code I have written:let express = require("express")let app = express();const MongoClient = require("mongodb").MongoClient;const url = 'mongodb://127.0.0.1:27017';const dbName = 'HospitalManagement';app.get('/hello',(req,res) => {// res.writeHead(200,{'Content-Type':'text/html'});console.log(req.query.hosp_name);// res.send("hello");let str;MongoClient.connect(url,{useUnifiedTopology:true,useNewUrlParser:true},(error,client) =>{if(error)return error;let db = client.db(dbName);db.collection('Hospital_Info').find().toArray((err,items) =>{if(err){return err;            }else{str = JSON.stringify(items);console.log(str);            }        });    });res.send(str);res.end();   });app.listen(8000,() =>{console.log("Server listening on PORT 8000");});​The line res.send(str) doesnt print anything in the browser. But if I uncomment res.send("hello"), it prints it. So I assume there is something wrong with the MongoClient function. Can anyone help me?

Submitted September 27, 2020 at 04:22PM by Vamsi_0

No comments:

Post a Comment