Express: The Most Popular Node Framework

2580 VIEWS

This article will introduce you to one of the most popular and downloaded Node.js frameworks, Express. Express is a minimal and flexible Node.js web application framework that provides some of the fundamental tools required to build web and mobile applications. Using Express, you can easily create a web server that is more maintainable, flexible and readable than using the HTTP Node module.

Why Express?

Quite frankly, there are several frameworks you could use. However, what you get with Express is an unopinionated, simple and elegant way to go about things. It is easy to learn, gives you more control, and teaches you a lot of the basics (including the HTTP methods, which we will also look at).

Installation and Setup

1. You should have Node.js and the npm (node package manager) installed. To install Node.js, kindly visit this link. The npm comes with Node.js, so once you have that installed, you’re good to go.
2. Confirm that both are installed by checking the version: ‘node –version’, ‘npm–version’.
3. Open the terminal or command prompt, navigate to your preferred project location, and type ‘npm init –yes’. This will create a package JSON file in the folder.
4. Finally, install express with ‘npm install express’.

Before we get into Express, lets take a look at the HTTP module and how it works so that we get a better understanding of why you should use Express.

 
//load the http module
const http = require('http');
 
//define the port
const port =4000
 
//create a server using the http module
const server = http.createServer(function(req, res){
  	//if it’s the root/homepage
  	if(req.url==='/'){
              	res.statusCode=200; //status code of 200 means OK
              	res.write("Hello world") //the write method will display Hello world on the page
              	res.end() // End the response
  	}
 
  	//if it’s the about page
  	if(req.url==='/about'){
              	res.statusCode=200
              	res.write("About page")
              	res.end()
  	}
});
//server should listen at a given port
server.listen(port, function(){
  	console.log("listening on port 4000...")
});
 

While this approach works, it’s not very maintainable. This is because as we define more routes for our application, we need to add more if blocks. Therefore, why not just use a simple, fast and unopinionated framework like Express that gives us more possibilities?

To get started with Express, let’s create our main module file in our project folder and name it ‘app.js’. Open that file in a text editor of your choice and load the Express module.

 
//app.js
//load the express module
const express = require('express'); // this function returns an object of type express
 
//by convention we call the object app
const app = express();
 

The app object has a bunch of useful methods that we will look at. These include methods like GET, POST, PUT and DELETE. These are some of the HTTP request methods. So, before we type any more code, we’ll need to understand what they’re used for.

  1. GET: The GET method is used to request a representation of the specified resource. GET requests only retrieve data.
  2. POST: The POST method is used to submit an entity to the specified resource. In other words, to create data.
  3. PUT: The PUT method is used for updating the specified resource.
  4. DELETE: The DELETE method deletes the specified resource

The following code will demonstrate how to use these HTTP requests in Express. We’ll create a simple server that allows us to retrieve a list of courses, create a course, update a course and delete a course.

We’re not dealing with databases, so we’ll simply create an array of JSON objects. To do that, we need to add a line of code to allow us to parse JSON objects. Consequently, we create the array.

 
//app.js
//…
//adding a piece of middleware to allow us to parse json objects
app.use(express.json());
 
//an array of course objects
const courses = [
  	{id: 1, name: 'Algorithms'},
  	{id: 2, name: 'Software Engineering'},
  	{id: 3, name: 'Human Computer Interaction'}
  	]
 

The following code will demonstrate how to use the GET method in defining routes.

  
//app.js
//…
//Defining a Route
 
//app.get takes 2 arguments, the first is path/url.
//The second argument is a callback function
//the callback function takes 2 arguments: the request and response
 
app.get('/', function(req, res){  //when we get an http get request to the root/homepage
  	res.send("Hello World");
});
 
//when we route to /courses
app.get('/courses', function(req, res){
  	res.send(courses); //respond with the array of courses
});
 
//To get a specific course, we need to define a parameter id
app.get('/courses/:id', function(req, res){
  	const course = courses.find(c => c.id === parseInt(req.params.id));
 
  	//if the course does not exist return status 404 (not found)
  	if(!course) return res.status(404).send('The course with the given id was not found')
 
  	//return the object
  	res.send(course)
  	
});

Next, we’ll look at how to use the POST request to create new data.

 
//using the http post request we can create a new course
app.post('/courses', function(req, res){
  	//create a course object
  	const course = {
              	id: courses.length+1,
              	name: req.body.name
  	}
 
  	//add the course to the array
courses.push(course);
  	
  	//return the course
  	res.send(course);
});
 

To test our POST request, we’ll use an application known as Postman. Kindly follow the simple steps below.

Set up and use:

1. Search for chrome postman

2. Add to Chrome

3. Click Apps to find Postman. Then open it.

4. There’s no need to sign up or log in. Instead, you can click the link to take you straight to the app.

5. Click the drop-down and select POST. Then, enter the URL (http://localhost:3000/courses) and click the body section.

6. Select “raw” and change the text to JSON. Consequently, add an object and give it a name property. Finally, click Send.


7. Scroll down to see the status of the request (200 is successful), and the body of the response. A new course has been created with an ID of 4.

The following code will demonstrate how to update a course using the PUT request.

 
app.put('/courses/:id', function(req, res){
  	//get the course
  	const course = courses.find(c => c.id === parseInt(req.params.id));
 
  	if(!course) return res.status(404).send('The course with the given id was not found');
 
  	//update the course
  	course.name = req.body.name;
 
  	//return the updated object
  	res.send(course)
 
});
 

With this example, we’ll update the course where the ID is 1 using the Postman app. Enter the URL and make sure to specify the ID (http:// localhost:3000/courses/1). Consequently, you may scroll down and look at the status and body.

The following code will demonstrate how to delete a course using the DELETE request.

 
app.delete('/courses/:id', function(req, res){
  	//get the course
  	const course = courses.find(c => c.id === parseInt(req.params.id));
 
  	if(!course) return res.status(404).send('The course with the given id was not found');
 
  	//get the index and delete it
  	const index = courses.indexOf(course);
  	courses.splice(index, 1);
 
  	//return the deleted object
  	res.send(course)
});

In the Postman app, kindly change the method to delete, enter the URL (make sure to include the ID), and click Send.

Following is the implementation to listen at a given port. Place this at the end of the app.js file.

//check if theres the environment variable PORT
const port = process.env.PORT || 3000;

//listen at a given port
app.listen(port, function(){
console.log("listening on port " + port)
})

There you go—You have now been introduced to the Express framework. Now it’s your turn to start building Express applications. The documentation is always a good place to start from.


Frederick Plange is a computer science major at Ashesi University, one of the top universities in Ghana aiming to develop ethical and entrepreneurial leaders to transform the nation. Frederick is a focused and goal driven individual that is passionate about technology and computers


Discussion

Click on a tab to select how you'd like to leave your comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Menu
Skip to toolbar