0

I have a node.js application that is getting a collection from MongoDB and returning it correctly. What is the simplist way I can display this information into HTML or React? I am going to be hosting this later, I tried using a MERN approach, but I feel like express was overkill as I am just trying to read the data. I also could not host the app when I used express. I do not need anything else.

const {MongoClient} = require('mongodb');
//https://www.mongodb.com/blog/post/quick-start-nodejs-mongodb--how-to-get-connected-to-your-database
//https://www.mongodb.com/blog/post/quick-start-nodejs--mongodb--how-to-read-documents


async function main(){
    /**
     * Connection URI. Update <username>, <password>, and <your-cluster-url> to reflect your cluster.
     * See https://docs.mongodb.com/ecosystem/drivers/node/ for more details
     */
    const uri = "mongodb+srv://mongodbTest:password@cluster0-bib2p.mongodb.net/test?retryWrites=true&w=majority"


    const client = new MongoClient(uri);

    try {
        // Connect to the MongoDB cluster
        await client.connect();

        // Make the appropriate DB calls
        await  listDatabases(client);
        await findOneListingByName(client, "o2");

    } catch (e) {
        console.error(e);
    } finally {
        await client.close();
    }
}

main().catch(console.error);

async function listDatabases(client){
    databasesList = await client.db().admin().listDatabases();

    console.log("Databases:");
    databasesList.databases.forEach(db => console.log(` - ${db.name}`));
};

async function findOneListingByName(client, nameOfListing) {
    result = await client.db("testing").collection("testcollection").findOne({ name: nameOfListing }
);

    if (result) {
        console.log(`Found a listing in the collection with the name '${nameOfListing}':`);
        console.log(result.data);
    } else {
        console.log(`No listings found with the name '${nameOfListing}'`);
    }
}
  • It's not overkill, you add it to your application and with few lines of code, you can serve up your content. also it can help you in future if you decide to add more pages to your app. – Mehdi Dehghani Jan 25 '20 at 06:06
  • Does this answer your question? [Using node.js as a simple web server](https://stackoverflow.com/questions/6084360/using-node-js-as-a-simple-web-server) – Mehdi Dehghani Jan 25 '20 at 06:10
  • @MehdiDehghani not quite I have a function in node.js that i returns a value I need displayed in my html/react – makingithappeninc Jan 25 '20 at 06:13
  • Share your code please. – Mehdi Dehghani Jan 25 '20 at 06:14
  • @MehdiDehghani this is my node.js file, the value I get for result.data logs correctly, but I need it displayed – makingithappeninc Jan 25 '20 at 06:18
  • I think [this answer](https://stackoverflow.com/a/13635318/3367974) will work for you, if you don't want to use any package. you can send anything to the client. for example you can send your data as json and then render it using JS – Mehdi Dehghani Jan 25 '20 at 06:35

1 Answers1

0

Based on this answer

With folder called assets contains app.css and jquery.js, also server.js and index.html with following content hopefully you could get your desired result.

server.js

const http = require("http");
const url = require("url");
const path = require("path");
const fs = require("fs");

const port = process.argv[2] || 8888;
const contentTypes = {
    '.html': "text/html",
    '.css':  "text/css",
    '.js':   "text/javascript"
};

http.createServer((req, res) => {
    let uri = url.parse(req.url).pathname;

    if (uri.indexOf('/api/getall') > -1 ) {
        // simulate database delay
        setTimeout(() => {
            res.writeHead(200, {"Content-Type": "application/json"});
            res.write(JSON.stringify({id: 10}));
            res.end();
        }, 1000);
    }
    else {
        let filename = path.join(process.cwd(), uri);

        fs.exists(filename, exists => {
            if(!exists) {
                res.writeHead(404, {"Content-Type": "text/plain"});
                res.write("404 Not Found\n");
                res.end();
                return;
            }

            if (fs.statSync(filename).isDirectory()) filename += '/index.html';

            fs.readFile(filename, "binary", (err, file) => {
              if (err) {        
                res.writeHead(500, {"Content-Type": "text/plain"});
                res.write(err + "\n");
                res.end();
                return;
              }      

            let headers = {},
                contentType = contentTypes[path.extname(filename)];

              if (contentType) headers["Content-Type"] = contentType;

              res.writeHead(200, headers);           
              res.write(file, "binary");
              res.end();      
            });
        });
    }   
}).listen(parseInt(port, 10));

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title></title>
    <link href='/assets/app.css' rel='stylesheet' />
</head>
<body>
    <h1>Hello world!</h1>

    <script src='/assets/jquery.js'></script>
    <script>
        $.ajax('/api/getall').done(res => console.log(res));
    </script>
</body>
</html>

Run the app using node server.js and head to http://localhost:8888/, you should see Hello world on the screen and { id: 10 } on browser console. from there you can decide how to render your data, e.g using react or mustache.js

Mehdi Dehghani
  • 8,186
  • 5
  • 49
  • 53