Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serving Dynamic Webpages with Node.js

I am having a hard time understanding how exactly node.js serves dynamic content. So let's say we have the following code that renders a home page:

var express = require('express'),
    app = express();

app.get('/', function(req,res){
    res.render('home.html');
});

However, let's say this home page was supposed to be a user profile in which you are pulling user information from a database, which results in code:

var express = require('express'),
    mongoose = require('mongoose'),
    app = express();

mongoose.connect('mongodb://localhost/ExampleDB');

app.get('/:id', function(req,res){
    User.findOne({_id: req.id}, function (err, user){
       var name = user.name;
       var profilePic_uri = user.profilePic_uri;
       res.render('home.html');
});

So, ideally home.html is just a template page, in which you set maybe the user's profile picture, their name, etc in the route handler. Right, because the idea behind node, is that this app.js should be able to handle pulling the dynamic content from a database at run time. Where I am having trouble is understanding how exactly rendering dynamic pages work with node. The html page is a static page. You can't really render a php or a asp page because, well, that doesn't really make sense does it?

Which leaves me with the question, how is it done?

like image 425
cg14 Avatar asked May 25 '15 18:05

cg14


People also ask

Can you host a website with node js?

If you're looking for a fast, scalable hosting option for your business (or any type of site), then you're right to be interested in Node. js!


1 Answers

If you add...

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

...after app=express() has been done then it will now default to the Jade rendering engine if you don't use an extension. Then in your router:

app.get('/', function(req,res){
  res.render('home', {
    var1: 'val1',
    var2: 'val2'
  });
});

You'd need to add Jade to your project's package.json file in the dependencies:

    "jade": "~1.9.1",

...and then "npm install" in your folder to bring that in.

Then you'd need a file named /views/home.jade with the contents:

doctype html
html
  body
    p Var1 is #{var1}
    p Var2 is #{var2}

You should see--when you visit your home page--that the values have been passed to the Jade rendering engine and expanded in place in the template as 'val1' and 'val2', respectively.

like image 125
Michael Blankenship Avatar answered Oct 07 '22 05:10

Michael Blankenship