This tutorial aims to provide an understanding of basic routing in Express.js. You will learn how to define different routes in Express and how to respond to various types of client requests.
By the end of this tutorial, you will be able to:
Before proceeding with this tutorial, you should have a basic understanding of Node.js and Express.js. Familiarity with JavaScript is also necessary.
Routing is a mechanism where HTTP requests are routed to the code that handles them. In Express.js, a route is a combination of a URL pattern and an HTTP method (get, post, put, delete, etc.), along with the code which should be executed when that route is matched.
Let's start with the most basic route in Express.js:
app.get('/', function(req, res) {
res.send('Hello World!')
})
In the above code, app.get()
is used to define a route. The first parameter is a string that represents the URL pattern. The second parameter is a callback function that will be executed if a GET request is made to the root URL ('/').
Express.js can handle different types of HTTP requests. Let's add a POST route:
app.post('/', function(req, res) {
res.send('Got a POST request')
})
const express = require('express')
const app = express()
const port = 3000
// Handle GET request
app.get('/', (req, res) => res.send('Handling GET request'))
// Handle POST request
app.post('/', (req, res) => res.send('Handling POST request'))
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))
In this example, when you navigate to 'http://localhost:3000', you will receive the message 'Handling GET request'. If you send a POST request to the same URL, you will receive 'Handling POST request'.
You've learned the basics of routing in Express.js, including how to handle different types of HTTP requests. Next, you could learn about more advanced routing concepts, such as route parameters and middleware.
Create an Express.js server that responds with "Hello, User!" to a GET request at '/user'.
Extend the above server to respond with "Creating a new user..." to a POST request at '/user'.
Further extend the server to respond with "Updating the user..." to a PUT request at '/user'.
Here are the solutions:
// Exercise 1
app.get('/user', function(req, res) {
res.send('Hello, User!')
})
// Exercise 2
app.post('/user', function(req, res) {
res.send('Creating a new user...')
})
// Exercise 3
app.put('/user', function(req, res) {
res.send('Updating the user...')
})
These exercises should help you get a better understanding of how routing works in Express.js. Keep practicing with different routes and request methods to solidify your understanding.