sublime
sublime

Reputation: 4161

Getting Started with express.js, serving a dynamic HTML

I'm writing a single page web application using node.js and express. After going through some online tutorials, I found out this is how express.js serves a client directory with HTML, javascript and css

app.use(express.static(__dirname + '/public'));

This works great except the fact that public directory has to have .html root file which is static. I'd like to know how can I serve a dynamic HTML file with this same approach.

I want to insert some data into the page for example "Hello user_name" at the top. How do I do that for this single file.

I want to only do it once, at the startup, after that my application will make rest API calls and get plain JSON responses which it will then put it in the page.

Upvotes: 1

Views: 7610

Answers (1)

Vahe Khachikyan
Vahe Khachikyan

Reputation: 241

You cannot use the express static server to serve dynamic files as far as I'm aware. In order to serve a dynamic HTML you need to use a templating engine, such as jade or any of these templating engines.

Jade is pretty straightforward to use and is supported by express by default. To set up jade, include the following lines in your app configuration block:

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

The first line sets your views directory - from which the template files would be served. Since you want to serve only an index file, this directory would contain your index.jade template. The second line sets jade as the templating engine.

Now, instead of using the static server to serve the index.html, you need to create a get route '/' to serve the index file, like so:

app.get('/', function(req, res) {
    res.render('index', {user_name: username});
});

Upvotes: 2

Related Questions