Newbiee
Newbiee

Reputation: 105

How to pass variable from node.js to html

I am a newbie of node.js developer

I am currently writing a program with below program structure:

view
 |
 |--- booking.handlebars (HTML program)
 |
routes
 |
 |--- booking.js (node.js JavaScript program)
 |

When users access "dashboard" page, "booking.js" will connect to mongodb to retrieve all the "bookings" records from the Database "Booking". Then, my target is to pass the fetched "bookings" object to "booking.handlebars" HTML file.

However, I cannot achieve this goal.

I have thought many alternatives, including searching the threads from stackoverflow, using global variable; generating JSON file and then read the JSON file back, etc. But it seems doesn't work.

I would like to seek your assistance that how can I pass all the object values from JavaScript program to HTML.

Below is my code:

booking.handlebars (HTML program)

<div>
    <div>
        <table>
            <tbody>
                <tr>
                    <td>{{user.username}}</td>
                    <td>{{booking}}</td>
                    <td>{{req.booking}}</td>
                    <td>{{bookingRecord}}</td>
                    <td>{{bookings.booking}}</td>

                </tr>
            </tbody>
        </table>
    </div>
</div>

booking.js (node.js JavaScript program)

var express = require('express');
var router = express.Router();
var bookingRecord = null;


router.get('/dashboard', function(req, res){
    res.render('dashboard');
});


router.post('/dashboard',
  function(req, res) {
    var MongoClient = require('mongodb').MongoClient;
    var url = "mongodb://localhost:27017/";

    MongoClient.connect(url, function(err, db) {
      if (err) throw err;
      var dbo = db.db("booking");
      dbo.collection("bookings").find().toArray(function(err, booking) {
        if (err) throw err;
        console.log(booking);
        bookingRecord = booking;
        db.close();
      });
    });

    res.redirect('/users/dashboard');
  });


module.exports = router;

Upvotes: 1

Views: 4577

Answers (1)

Ş&#252;kSefHam
Ş&#252;kSefHam

Reputation: 167

If you want send data from node.js to html,You should use ejs module.For get results from database you should use mongoose module.I understand you ;but i write on phone and i cant write code.

If you can get result of bookings with mongoose or without mongoose,you can send with express to html like this.

For use ejs file with express.js

app.engine('.ejs', ejs.__express);app.set('views',__dirname+'/views');

For send to html:

res.render('./dashboard.ejs',{booking:booking})

In dashboard.ejs:

<span><%-booking.username%></span>//booking is what you sent with res.render  

Note1 create viesw folder and create dashboard.ejs in views folder. Note2 install ejs and mongoose modules.

Upvotes: 1

Related Questions