DEV Community

Cover image for Learning Express.js
Maasa Kono
Maasa Kono

Posted on

Learning Express.js

As developers, we use all sorts of frameworks to speed up the process of building web applications, reducing time spent on writing repetitive code. Express is one such handy framework.

Per the Express JS website, it is a "fast, unopinionated, minimalist web framework for Node.js."

I like the sound of that!

Here's what The Net Ninja has taught me about it.

What is Express?

Express is a web application framework for Node.js that has several benefits, including:

  • easy and flexible routing system
  • integrates with many templating engines
  • contains its own middleware modules for additional functionalities on requests and responses
  • easily serve static files and resources of the application
  • easily connect with databases

Installation

To install Express, run the following in the terminal (assuming we already have Node.js installed):

$ npm install express
Enter fullscreen mode Exit fullscreen mode

Once the installation is complete, let's require the Express module in our main app.js file, set a variable (in this case we will set it as app), and fire express(). We will also need to set up a port, which we can listen to. For our purposes, we'll use the commonly used port 3000.

app.js

// Require the Express module
const express = require('express');

// Fire Express and set it to a variable
const app = express();

// Listen to port 3000
app.listen(3000);
Enter fullscreen mode Exit fullscreen mode

Now we have access to the functionalities offered by Express!

Routing

As we know, we make various HTTP requests to determine how our application responds. The HTTP verbs with the corresponding Express functionalities are as follows:

// GET 
app.get('route', fn);

// POST
app.post('route', fn);

// PUT
app.put('route', fn);

// DELETE
app.delete('route', fn);
Enter fullscreen mode Exit fullscreen mode

Pretty straightforward!

The function that gets passed into the above HTTP request methods take two parameters: a request object and a response object. The response object has a property of send, wherein we can specify what we want to send back.

The following is a very basic example of a GET request for the root path ('/') with a simple string response:

app.get('/', function(request, response) {
  response.send('This is the root page');
});
Enter fullscreen mode Exit fullscreen mode

This, however, is not typically how we would send responses - instead, we would be sending back various files. The response object also has access to a function sendFile() which takes a parameter of the file name we want to respond with.

If we take the example above and instead want to send the actual index.html root file, then we would code it as follows:

app.get('/', function(request, response) {
  response.sendFile(__dirname + '/index.html');
});
Enter fullscreen mode Exit fullscreen mode

Route Parameters

To dynamically access certain parameters in the route, we can use the params property of the request object.

Let's say we are on a Dragon Ball Z website, looking at a directory of Saiyans. We could pass in a parameter of :name to identify which Saiyan's page we want to request, and have access to it through the request object as follows:

app.get('/saiyan/:name', function(request, response) {
  res.send('The Saiyan you are currently viewing is ' + req.params.name);
});
Enter fullscreen mode Exit fullscreen mode

So if our URL is localhost:3000/saiyan/goku, req.params.name will equal goku.

Template Engines

Template engines allow us to use static template files in our application, replacing variables with values at runtime, and making the template into an HTML file that can be sent to and read by the client.

With a JavaScript template engine, we can embed JavaScript code into HTML files, dynamically injecting content.

EJS is one such template engine. It is just like ERB in Ruby (for those of you who may be a Rubyist).

To install the EJS package, run:

$ npm install ejs 
Enter fullscreen mode Exit fullscreen mode

Then we need to let Express know that we want to use EJS as our view engine:

app.set('view engine', 'ejs');
Enter fullscreen mode Exit fullscreen mode

By default, when making a request for views/templates, EJS will look in the views folder, so we will need to create this directory and put all views/templates inside here.

All EJS file names must end with .ejs in order for the engine to recognize it.

When we want to respond with an EJS file, we use the render method on the response object, instead of sendFile(). This takes a parameter of the EJS file name, but we can exclude the .ejs part.

Let's say that, instead of sending the index.html file, we are now going to send an index.ejs file (which is inside the views folder). Our code would now look like this:

app.get('/', function(request, response) {
  response.render('index');
});
Enter fullscreen mode Exit fullscreen mode

We can pass data to a view by passing an object as a second parameter to the render() function.

Let's take a prior GET request for a particular Saiyan's web page. In this example, we'll create a data object with properties of level and job. Then, we will call the render() function, passing in the saiyan EJS file (which we will get to in just a second), along with a second parameter of an object:

app.get('/saiyan/:name, function(request, response) {
  const data = {level: 3, job: 'hero', friends: ['Krillin', 'Bulma', 'Muten Roshi']};
  response.render('saiyan', {warrior: req.params.name, data: data});
});
Enter fullscreen mode Exit fullscreen mode

Now let's create a saiyan.ejs file under the views directory. This will look mostly like an HTML file, but wherever we are embedding data, we will use <%= %>:

views/saiyan.ejs

<!DOCTYPE html>
<html>
<head>
  // We won't worry about this section for now
</head>
<body>
  <h1>Saiyan's Name: <%= warrior %></h1>
  <h2>Level: <%= data.level %></h2>
  <h2>Job: <%= data.job %></h2>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

We can also output JavaScript with data:

  <% data.friends.forEach(friend => { %>
    <li><%= friend %></li>
  <% }); %>
Enter fullscreen mode Exit fullscreen mode

Notice that we are not using the equal sign where we're not actually rendering data.

Partial Views

Partial templates are for parts of a page that can be used across multiple views, such as a navigation bar. The benefits of using partial templates include:

  • eliminating repetitive code
  • any change that needs to be made only need to be made once in a partial view

Under the views directory, we can create another directory called partials, and in here we can create partial template files (views/partials/navbar.ejs). All we need to do to include a partial template in another view file is to use the following syntax:

<html>
<body>
  // Include the navbar partial template here
  <%-include('partials/navbar.ejs') %>

  // The rest of the body content
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

There's much more to Express, but that's about it for this little introduction. I hope it helps!

Happy coding~~~ 😄

Helpful Link

The Net Ninja's Express tutorial videos

Top comments (1)

Collapse
 
hwolf0610 profile image
Harry Naruto

I think so.
ExpressJs is good way to development fast Backend with NodeJS.