Node JS Tutorial - Introduction to Express

In this tutorial, we will learn about the Express framework, an extensible web framework built for the Node.js ecosystem. Express enables you to create a web server that is more readable, flexible, and maintainable than one created using only the Node HTTP library, which can become complicated even for basic web servers.

Creating a New Express Project

Let's create a new Express project. First, navigate to the project location. In this example, we will create a project on the desktop. Create a new folder, for instance, "expresspro". Open this folder and then open the command prompt by typing "cmd" in the file explorer URL and pressing Enter.

Inside the command prompt, run the following command:


npm init

Next, install the Express module by running the command:


npm install --save express

Now, open the project in Visual Studio Code. Create a new file called "index.js" and open it. Inside the index.js file, require the Express framework module:


const express = require('express');

Set up the Express application, create a route, and return a text:


const app=express();
app.get('/', (request, response) => {
response.send('hello world');
});
app.listen(3000, ()=> {
console.log('Express intro running on localhost:3000');
});

The app.listen() function tells the server to start listening for connections on a particular port, in this case, port 3000.

Running the Express Application

Let's run the application. Switch to the command prompt and run the command:


node index.js

The application is now running on localhost:3000. Let's check it out. Switch to the browser and navigate to the URL localhost:3000. You should see the message "hello world".

Creating Simple Routes in Express

Let's create some simple routes in Express. Go back to the index.js file and add the following routes:


app.get('/home', (request, response) => {
response.send(Home Page');
});
app.get('/about', (request, response) => {
response.send('About Page');
});
app.get('/contact', (request, response) => {
response.send('Contact Page');
});

Run the application again by switching to the command prompt and running the command:


node index.js

The application is now running. Go back to the browser and refresh the page. Add "/home" to the URL, and you should see the home page. Navigate to "/about", and you should see the About Page. Finally, go to "/contact", and you should see the Contact Page.

This is how you can create a new Express project and set up simple routes.