Search code examples
javascriptnode.jsrestify

Make the variables in Node module usable by jQuery, Ember, etc


I'm really new to the world of backend, and I'm trying to have the variables that I made within a Node module (called app.js) accessible by other ordinary JavaScript modules. The data within the said variables is from MongoDB, if that matters.

So far I can only res.send() the data as boring plain text on the page. I want to be able to manipulate this data for other purposes (such as making a table). So how can I pass these variables to JavaScript, and so I can display them properly in HTML?


Solution

  • You can use res.render to pass the data to a rendered web page, with express and jade it looks like this:

    res.render('yourView', {
        data: yourVariable
    }
    

    Res.render will go where you have your res.send. Which should either be with your app initialization (app.js) or in an external file like (router.js), that is then fed to your app.

    Then in the template used as the web page you can call it like this:

    #{data}
    

    Or you can make a list like this (if you are using jade)

    each data in rows
        li= data
    

    Hope this is what you meant, and helps :D.

    An example of what app.js might look like now:

    var express = require('express');
    var http = require('http');
    var bodyParser = require('body-parser');
    var methodOverride= require('method-override');
    var routes = require('./routes')(app);
    var path = require('path'); 
    var app = express();
    
    app.configure(function() {
        app.set('port', process.env.PORT || 3000);
        app.set('views', __dirname + '/views');
        app.set('view engine', 'jade');
        app.use(bodyParser.urlencoded({extended: true}))
        app.use(bodyParser.json())
        app.use(methodOverride());
        app.use(express.static(path.join(__dirname, 'public')));
    })
    
    app.get('/', function(req, res){
        res.render('home', {
            title: "Welcome to an example site"
        });
    });
    
    http.createServer(app).listen(('3000'), function(){
        console.log('Server Online');
    });