Introduction to Express
In this article you will learn about routing in NodeJS with Express. We will teach you the basics of Express and the NodeJS engine.
What is routing?
Routing is a method which tells how an application should respond to a client request at a particular path and a specific HTTP request method (GET, POST, PUT and so on).
To put it simply, routing ****instructs which function gets invoked whenever the user navigates to a particular URL. In this context, URL refers to any path.
Let’s use a simple note taking app as an example:
- If the user goes to the
/notes/add
route, the server should perform a POST request and add an entry to the database. - Alternatively, if the user navigates to
/notes/myNote
, the app should perform a GET request and retrieve the document with the title ‘myNote
‘ from the database.
Defining routing methods
You define routing methods using the following syntax:
app.METHOD(PATH,CALLBACK)
This method tells the server, “If a user navigates to PATH
, then execute CALLBACK
and perform an HTTP METHOD
request.”
Here, the most commonly used verbs in place of METHOD
are:
get
: To handle GET requests (i.e. to request/GET ****data from a specified resource).post
: To send data to a server to create/update a resource.put
: To send data to a server to create/update a resource.delete
: For removal of a specified resource.
In this article, you will learn how to use Express to handle routing functionality in your app.
Now that we have covered the fundamentals terms for routing, let’s write some code!
Basic Usage
Project setup
Before writing some code, first setup your project repository like so:
mkdir routingWithExpress
cd routingWithExpress #go into directory
npm init -y
When that’s done, install the express
module like so:
npm install express
To learn about the basics of NPM, click here.
Writing a ‘Hello World’ program in Express
In your project directory, create a new file called helloWorld.js
. Here, write the following code:
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
- Line 1: Import the
express
module in our project. This will let us implement routing functionality in our app. - Lines 5-7: Tell the app that if the user goes to the
/
(home) directory, then show aHello World
message to the user. - Lines 9-11: The
listen
method tells Express to run the app at thelocalhost:3000/
URL. If the client uses their web browser to navigate to this page, the program will execute a GET request.
Let’s test it out! Run the program like so:
node helloWorld
This will be the output:
Sending POST requests With Express
Via the app.post
method, you can perform POST requests to send data to the server like so:
const express = require("express");
const app = express();
const port = 3000;
app.use(express.text());
app.get("/", (req, res) => {
res.send("Get request. Hello World!");
});
app.post("/", (req, res) => {
res.send(`Post request. data received:${req.body}`);
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
Here’s a brief explanation of the code:
- Line 4: The
use
method instruct Express to use middleware to parse text data. Middleware functions are pieces of code which run before every request. We will learn about this in detail in future articles. - Line 10: If the user performs a
POST
request, log out the request body on to the console.
In order to test out the code, we need to first submit a POST request via an API client like Thunderclient or Postman.
This will be the output:
Conclusion
Express is a robust and secure technology that lets developers engineer routing with minimal effort. Its documentation is clear and concise, which means that it requires little to no time to get up and running.
Thank you so much for reading!