Get in touch
or send us a question?

[Node.js Tutorials for Beginners] – Unit 10: Express framework part 2 (end)

Table of Contents

1. Templating

2. Sample Structure of a Node Express app

1. Templating

What is middleware?

You might hear the term middleware thrown around a lot but what is it in the context of Express.js? Middleware is any number of functions that are invoked by the Express.js routing layer before your final request handler is, and thus sits in the middle between a raw request and the final intended route. It basically lets you configure how your express application works.

In order to add middleware we will do the following:

Go to terminal and in the root create a folder called Public and add an html file inside

mkdir public
cd public 
touch demo.html

Paste the following code in the demo.html file

<!DOCTYPE html>
    <meta charset="utf-8">
    <title>Express Demo Page</title>
    <h1>Express Demo Page</h1>
    <p>Hello Express Template</p>

Let’s add some middleware by going to the server.js file & adding the following code:

Now run the unit10.js to see the result:

$ node unit10.js

Go to your browser and go to port 8081:


2. Sample Structure of a Node Express app

Node and Express don’t come with a strict file and folder structure.

controllers/ — defines your app routes and their logic. You main route might be index.js but you might also have a route called for example ‘/user’ so you might want to make a JS file that just handles that.

helpers/ — code and functionality to be shared by different parts of the project

middlewares/ — Express middlewares which process the incoming requests before handling them down to the routes

models/ — represents data, implements business logic and handles storage

public/ — contains all static files like images, styles and javascript

views/ — provides templates which are rendered and served by your routes

tests/ — tests everything which is in the other folders

app.js — initializes the app and glues everything together

package.json — remembers all packages that your app depends on and their versions

Thank you for reading!