In this tutorial, we will delve into the management of routes in Express.js, a minimal and flexible Node.js web application framework that provides features for web and mobile applications.
By the end of this tutorial, you will be able to:
Routes refer to how an application responds to a client request for a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).
Each route can have one or more handler functions, which are executed when the route is matched.
Here is a basic example:
app.get('/', function (req, res) {
res.send('Hello World!')
})
Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the req.params object, with the name of the route parameter specified in the path as their respective keys.
Here's how you can handle route parameters:
app.get('/users/:userId', function (req, res) {
let userId = req.params.userId;
res.send('User Id is ' + userId)
})
Express.js supports methods that correspond to HTTP request methods: get, post, put, delete, etc. Here's an example on how to handle a POST request:
app.post('/users', function (req, res) {
res.send('Got a POST request at /users')
})
const express = require('express')
const app = express()
// A route defined for GET request at the homepage
app.get('/', function (req, res) {
res.send('Welcome to the homepage!')
})
app.listen(3000)
When you run this code and visit 'http://localhost:3000' in your browser, you should see 'Welcome to the homepage!'
const express = require('express')
const app = express()
// Route with a 'name' parameter
app.get('/users/:name', function (req, res) {
res.send('Hello ' + req.params.name)
})
app.listen(3000)
In this example, if you visit 'http://localhost:3000/users/John', you should see 'Hello John' on the screen.
In this tutorial, we've covered the basics of route management in Express.js, including defining routes, handling route parameters, and implementing different HTTP request methods. For further learning, consider exploring middleware, error handling, and template engines in Express.js.
/products/:productId
and responds with the product ID.Solution:
JavaScript
app.get('/products/:productId', function (req, res) {
res.send('Product ID: ' + req.params.productId)
})
Visit 'http://localhost:3000/products/1234' in your browser. You should see 'Product ID: 1234'.
/users
.Solution:
JavaScript
app.post('/users', function (req, res) {
res.send('Got a POST request at /users')
})
You can use Postman or any other API testing tool to send a POST request to 'http://localhost:3000/users'. You should see 'Got a POST request at /users' as the response.
Keep practicing with different routes, request methods, and parameters to get a stronger grasp on Express.js routing.