Click here to Skip to main content
15,884,472 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My apologies if this has been asked before but I can't seem to find anything on it. I am currently trying to run a GET operation but my code doesn't seem to work. I already have the simple set up done but when I click the button I created to request the data from a simple .JSON file I made I keep getting "0 documents retrieved". Could anyone assist with this? here is my code. Any and all help is appreciated. Thank you.

Handlebars -

<!DOCTYPE html>
<html>
<head>
    <title>Get Request</title>
</head>
<body>
    <h2>GET Request</h2S>
    <div class="results">
        {{#each data}}
        <p> {{first_name}} {{last_name}} </p>
        {{/each}}
    </div>
</body>
</html>


HTML -

<h2>GET Request</h2>
<p>
 <a href="/api/user"
 data-selector="results">Load user data</a> 
 <form action="/api/user" method="GET"></form>
</p>
<div class="results"></div>


JavaScript -

const express  = require("express")
const app = express();
const mongo = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017/test';
var bodyParser = require('body-parser'); 
var exphbs  = require('express-handlebars');
 
app.set('view engine', 'handlebars');
app.engine('handlebars', exphbs());

 
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({extended: true}));

app.get('/api/user', function(req, res) { 
    mongo.connect(url,{ useUnifiedTopology: true }, function(err, database) {
        const db = database.db('test');
        db.collection('users').find() 
            .toArray(function(err, result) { 
            if (err) { 
                throw err; 
            } 
            console.log(result.length + ' documents retrieved.'); 
            //res.json(result); 
            res.render('user', { data:result, layout:false})
            database.close(); 
        }); 
    }); 
});


app.get('*', function (request, response) {
    response.sendFile('./public/hello.html',{root: __dirname});
});

 
const port = 8900;
app.listen(port);
console.log(`Listening to server: http://localhost:${port}`)


JSON -

{
    "id": 1,
    "name": {
        "first_name": "Robert",
        "last_name": "Swanson"
    },
    "title": "Some Dude"
}


What I have tried:

So far I have tried a couple different things such as changing the names in the array and messing around with the expression names in the handlebars file but since VSC isn't throwing any errors I don't really know exactly where to start.
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900