In this article, we’ll understand how node.js express framework and view engine works using different node packages.
While Node comes with a built-in module to work with HTTP and HTTPS, and even HTTP/2, these modules are low-level and they offer limited capabilities.
For example, there is no API to read body parameters from a POST request. you have to manually parse the text, which you can do using other Node built-in modules. but, because of this fact, a number of web frameworks have surfaced in the Node ecosystem to provide a richer interface to create and work with web servers.
These frameworks usually wrap the underlying built-in power in Node and give you a simpler API to create more complicated features in your web servers. The most popular options are the ExpressJS framework.
So, let’s create an express-based web server example,
Let’s go and create an index.js file which is the starting template of an express server. But the first thing that you need to do really is to bring express here as a dependency, and for that, we need to use NPM install.
const express = require('express');
const server = express();
server.listen(4253, () => {
console.log('Express server is working...');
});
And to use NPM install you should have a package.json. So, the first step is to create a package.json, we can use the “npm init” command here,
$ npm init --yes
and we’re going to do –yes to get the defaults of npm init, and this command will create a package.json file for us. Here is package.json here. Once we have package.json like that,
we bring in the express dependency using NPM install express. This will download express, place it under the node_modules folder, and as you can see,
$ npm i express
It documented that we started depending on express for this project. If you look under the node_modules folder now, you’ll see a lot more dependencies than express,
all of these packages are now part of your project dependencies. To use express, we require to express using the require function. The express package exports its top-level API as a function.
const express = require('express');
So, when captured the returned API into a local variable here, which is usually named express as well, that express variable in our script is now a function. And this is why, to create an express server, we just call this function.
const server = express();
The result of calling this express function is an object that’s usually named server. Now to make this server object listen to incoming requests from users of this web server, we call the listen method on it, which is very similar to the method we used to create a web server using the built-in HTTP module in Node.
server.listen(4253, () => {
console.log('Express server is working...');
});
It takes a callback that gets invoked when the listen operation is done. Now here’s where express is a bit different than the built-in module. We don’t define a single request listener. We define many listeners. We actually define a listener per URL. For every URL and HTTP operation that we want our server to support, we define a listener.
For example, usually the first URL that you want to support is the root URL. We use the following syntax to do that.
const express = require('express');
const server = express();
server.get('/', (req,res) => {
res.send('Hello Express');
});
server.listen(4253, () => {
console.log('Express server is working...');
});
We do the server get, specify the URL in the first argument for this get function. So, slash here as a string, and the second argument is the listener function that receives both the request and response object.
$ nodemon index.js
Let me just send a string here, “Hello Express”, and let’s run this code with Nodemon. the Nodemon index.js here should run our express server. So with this simple code, the server will start accepting connections and requests, and if the request matches one of the defined URLs, the listener for that URL will be invoked. So when we go to the root endpoint in a browser, using the port we passed in the listen to function,
Using Template Languages for Node
One of the most popular needs when working with Web Servers is to work with a template language to deliver static HTML that’s generated based on some data. Without a templating language, you would need to do a lot of string concatenation to accomplish that task.
There are a few great options when it comes to template languages with Node, and most of these options work with the big Web frameworks like Koa and Express. The most popular templating language in Node is probably pug, which used to be named Jade. This is a simple language implementing the offside-rule, which means that the HTML nesting is based on indentation.
Another templating language in Node. js is Handlebars. This is the same language that the Ember framework uses simple and feature-rich. But the simplest templating language that you can use is probably EJS, for Embedded JavaScript. You get a template language to write HTML views, and you can embed JavaScript while doing so. we’ll see how EJS can use with Express.
you’ll see at the package.json, we have the two dependencies now, express and ejs, and to bring these dependencies,
you need to run the npm install command without any arguments.
$ npm i
Now look at index. js, this is the same example that we’ve seen without ejs, and here are the differences.
const express = require('express');
const server = express();
server.set('view engine', 'ejs');
server.get('/', (req,res) => {
res.send('Hello Express');
});
server.listen(4253, () => {
console.log('Express server is working...');
});
We instruct express to set the view engine to ejs, this is the only line that’s needed for configuring express to work with ejs, you set the view engine to ejs. And then, inside of the request listeners, instead of. here we render index,
server.get('/', (req,res) => {
res.render('index');
});
This means, render one of the templates, which express finds by default under the views directory, inside this folder. So, if you look at the views directory, you’ll notice that I have an index.ejs and an about.ejs and these are two templates. that is being used to render HTML to the requester when they go to / and /about.
So, the index.ejs has a “Hello EJS Tutorial” h2 element,
<!DOCTYPE html>
<html lang="en">
<head>
<title>Welcome to Express</title>
</head>
<body>
<h2>Hello EJS Tutorial</h2>
</body>
</html>
And the about.ejs has an “About Page” h2 element.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Welcome to Express</title>
</head>
<body>
<h2>About Page</h2>
</body>
</html>
And if you run the server, and after that go to the port that we use, you’ll see the index.ejs template, and if you go to /about, you’ll see them about.ejs template. And this is all HTML that’s coming from the templating language. And because it’s all embedded JavaScript, you can embed JavaScript.
Let’s put a div here, and inside the div, we’re going to embed some JavaScript. You use this syntax here, and inside of that, you can put any JavaScript expression. like a Math.random(), for example,
<!DOCTYPE html>
<html lang="en">
<head>
<title>Welcome to Express</title>
</head>
<body>
<h2>Hello EJS Tutorial</h2>
<div>
<%- Math.random -%>
</div>
</body>
</html>
and this will give me a random value when I refresh the template for ejs. There you go, embedded JavaScript templating language. Very powerful. Now, this syntax is specific to ejs, other languages will have different syntax for embedding JavaScript.
Saved as a favorite, I really like your blog!
Pretty! This has been a really wonderful post.
Many thanks for providing this information.