Express Js Tutorial For Beginners

Express Js Tutorial For Beginners

In this tutorial you will learn about:

- What is Express JS

- Why Use Express

- Node.js and Express installation

- Basic Server Syntax on Express

- Basic Routing on Express

- Basic MVC on Express

This is an express tutorial for beginners.

If you are a beginner, then you will love this tutorial.

I will explain it very simply so that you can understand it well.

Let's get started.

 

#1. What is Express?

Express is Fast, unopinionated, minimalist web framework for Node.js.

Express is a "server-side" or "backend" framework that is very reliable in building APIs (Application Programming Interface).

 

#2. Why Use Express?

- Express makes it easy to build web-based applications with node.js

- Very light, fast, and free.

- Provides convenience in building routes.

- Provides full control over requests and responses.

- Express is the most popular web framework for node.js

 

#3. Node.js Installation

To install express, you need to install node.js first on your computer.

You can visit the following url to download node.js:

https://nodejs.org

Download according to your operating system then install.

It is highly recommended to download the latest version of node.js.

After a successful installation and to make sure node.js is installed on your computer, you can type the following command in Terminal or Command Prompt:

node –v

Like the following picture:

node version

In the picture above, you can see I am using node.js v14.14.0.

When you install node.js, it will automatically included NPM (Node Package Manager).

You can type the following command at the terminal or Command Prompt to make sure NPM is installed on your computer:

npm –v

Like the following picture:

npm version

In the picture above, you can see I am using NPM v6.14.8.

 

#4. Install Express Using NPM

You can install express easily using NPM.

Apart from that, you can also install all the dependencies you need in building web applications using NPM.

Create a folder on your computer, here I name it "express-app".

If you make it with the same name, that's even better.

You are free to create it anywhere, whether on C, D, or on the Desktop.

This folder will be our project folder later.

Then open the folder using a code editor, here I am using “Visual Studio Code”.

I also recommend you to use “Visual Studio Code”.

You can download “Visual Studio Code” at the following link and install it on your computer:

https://code.visualstudio.com/

Next, open a terminal in Visual Studio Code on the terminal menu bar, then type the following command:

npm init –y

Like the following picture:

npm init

The command will create a file called "package.json" in the "express-app" folder.

This file contains all the dependency and package information that we use in building the application.

Next, install express by typing the following command in the terminal:

npm install express

Like the following picture:

npm install express

The above command will install the express framework automatically in the "express-app" folder.

If you open the "package.json" file, you will see an added dependency, namely "express" as follows:

{
  "name": "express-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  }
}

In addition, there is an additional "node_modules" folder in the "express-app" folder.

At this point, you have successfully installed express.

 

#5. Basic Server Syntax on Express

Before getting into the basic server syntax on express, first add the following code to the "package.json" file:

"type": "module",

So that the "package.json" file looks like this:

{
  "name": "express-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  }
}

This is so that we can use the ES6 Syntax Module.

Next, create a file called "index.js" in the project root equivalent to the “node_modules” folder and the “package.json” file.

Like the following picture:

index js

Open the "index.js" file, then type the following code:

//import express
import express from "express";

// init express
const app = express();

// basic route
app.get('/', (req, res) => {
    res.send('Hello World');
});

// listen on port
app.listen(3000, () => console.log('Server Running at http://localhost:3000'));

The code above is the basic server code on express.

We import express with code:

import express from "express";

Initialize express with the command:

const app = express();

Then create a basic route with code:

app.get('/', (req, res) => {
    res.send('Hello World');
});

And run the server on port 3000 with the following code:

app.listen(3000, () => console.log('Server Running at http://localhost:3000'));

To run the server, you can type the following command into the terminal:

node index

Like the following picture:

node index

Next, open your browser and visit the url: http://localhost:3000.

If it goes well, you will see the message "Hello World" as shown below:

hello world

 

#6. Multiple Route on Express

In the segment above, we have created a route that is to display the message "Hello World".

We can also create multiple routes as an example:

multiple routes

Open the "index.js" file, then change it to be like the following:

//import express
import express from "express";

// init express
const app = express();

// Home route
app.get('/', (req, res) => {
    res.send('Welcome to Home Page');
});

// About route
app.get('/about', (req, res) => {
    res.send('Welcome to About Page');
});

// Contact route
app.get('/contact', (req, res) => {
    res.send('Welcome to Contact Page');
});

// listen on port
app.listen(3000, () => console.log('Server Running at http://localhost:3000'));

Then, restart the server by typing the following command in the terminal:

node index

Like the following picture:

node index

Next, open your browser and visit the url: http://localhost: 3000.

If it goes well, you will see the message "Welcome to Home Page" as shown below:

home page

Visit url: http://localhost:3000/about, to access the about page:

about page

And visit url: http://localhost:3000/contact, to access the contact page:

contact page

 

#7. Router on Express

In the previous segment we discussed multiple routes on express.

If you pay close attention, the route and program logic are in one file, namely "index.js".

For starters that is a good thing, but if you are building a more complex application and need lots of routes, it's not a good idea.

Therefore, express provides a feature, namely "Express Router".

Using the express router, we can create separate routes from "index.js".

Thus, we can create more complex routes.

To better understand how the express router works, please create a folder called "routes" which is equivalent to the “node_modules” folder.

Then create a file called "routes.js" in the "routes" folder as shown below:

routes js

Then type the following code in "routes.js":

// import express
import express from "express";

// init express router
const router = express.Router();

// Home route
router.get('/', (req, res) => {
    res.send('Welcome to Home Page');
});

// About route
router.get('/about', (req, res) => {
    res.send('Welcome to About Page');
});

// Contact route
router.get('/contact', (req, res) => {
    res.send('Welcome to Contact Page');
});

// export default router
export default router;

Then open the "index.js" file and change it to be like this:

//import express
import express from "express";

// import router
import Router from "./routes/routes.js";

// init express
const app = express();

// Use Router
app.use(Router);

// listen on port
app.listen(3000, () => console.log('Server Running at http://localhost:3000'));

In the code above, you can see that we separate the routes with "index.js".

Thus, the code in the "index.js" file looks cleaner.

This is possible because we are exporting the “routes.js” file with code:

export default router;

Then we import the router in the "index.js" file with the code:

import Router from "./routes/routes.js";

After that, we can use the route in the "index.js" file with the following code:

app.use(Router);

If you restart the server with the command:

node index

Then everything is still running as before.

 

#8. Basic MVC on Express

In the previous segment you learned how to separate routes with "index.js".

If you notice more detail, then you will find that the program logic lies in the file "routes.js".

Although in the above case there is no complicated program logic, it only displays a message "Welcome to Home Page" and so on, this is not a solution if you are creating an application that has complex program logic.

Therefore, we can use the MVC (Model-View-Controller) pattern.

MVC is a modern design pattern that separates program code into 3 parts: Model, View, and Controller.

Model: Contains program code that handles the structure and communication of data with the database.

View: Contains code that handles interactions with the client and user interface.

Controller: Contains program code that handles all program logic connecting the Model and View.

In modern web applications, the MVC pattern is implemented slightly differently.

This is because in modern web applications, the backend and frontend are built separately.

This functions so that applications that are built are easier to develop in the future as a team.

Therefore, the backend only applies the Model and Controller concepts, while the View is implemented on the frontend.

Express is a framework for "Backend", so we can apply the concept of Model and Controller.

Even though express is a backend framework, it does not mean that it is impossible to implement the MVC concept totally.

You can use view engines such as: Handlebars, EJS, or pug for views.

For small-scale applications it is good practice, but if you build large-scale applications it will be difficult to develop at a later date.

The best practice is to separate the Backend and Frontend.

In this case, we will separate the program logic with routes by creating a Controller.

Therefore, create a folder called "controllers" which is equivalent to the “node_modules” folder.

Then create a file called "page.js" in the "controllers" folder as shown below:

page js

Open the “page.js” file in the “controllers” folder then type the following code:

// Home page
export const Home = (req, res) => {
    res.send('Welcome to Home Page');
}

// About Page
export const About = (req, res) => {
    res.send('Welcome to About Page');
}

// Contact page
export const Contact = (req, res) => {
    res.send('Welcome to Contact Page');
}

Then open the “routes.js” file in the “routes” folder, then change it to the following:

// import express
import express from "express";

// import page controller
import { Home, About, Contact } from "../controllers/page.js";

// init express router
const router = express.Router();

// Home route
router.get('/', Home);

// About route
router.get('/about', About);

// Contact route
router.get('/contact', Contact);

// export default router
export default router;

In the code above, you can see that the code in the “routes.js” file looks cleaner and doesn't have any programming logic in it.

You can place all program logic in the controllers file.

You can also apply Models if you want to interact with the database. However, in this case we are not using a database.

This is a great application structure for building large-scale web applications.

Although in the above example there is no programming logic that stands out in the controller, you can understand very well the structure of a good application.

You can easily learn program logic, build APIs, interact with databases, and so on with this structure.

If you restart the server by typing the following command into the terminal:

node index

Then everything will go as before.

Visit the url: http://localhost:3000. To access the Home page:

home page

Visit the url: http://localhost:3000/about. To access the About page:

about page

And visit the url: http://localhost:3000/contact. To access the Contact page:

contact page

 

Conclusion:

In this tutorial you have learned the basics of express js.

You have also learned how to create separate routes using an express router.

Not only that, you have also learned how to structure a good application by applying the MVC pattern to express js.

So what are you waiting for, Let's Coding!

Download Source Code

Comments (1)

Jörg Hartgen, 11 December 2021 05:48 -

Thanks a lot for this useful and clear introduction. One suggestion: You may want to mention that one has to save the files (Ctrl + S) in Visual Studio Code after writing or changing the code, otherwise there will be errors.

Leave a Comment