Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It facilitates the rapid development of Node-based web applications. Express simplifies routing, handling HTTP requests, rendering HTML views, and managing middleware.
Routing in Express.js refers to how an application’s endpoints (URIs) respond to client requests. It determines 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, etc.).
First, ensure Node.js and npm (Node Package Manager) are installed on your system. Then, create a new project directory and initialize a Node.js project:
mkdir express-routing-example
cd express-routing-example
npm init -y
Install Express.js using npm:
npm install express
Create an app.js
file and set up a basic Express server:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Run the server:
node app.js
Navigate to http://localhost:3000
in your browser. You should see “Hello, World!”.
Express.js provides methods to define routes for various HTTP methods. The most common methods are:
app.get()
: Defines a route for the GET method.app.post()
: Defines a route for the POST method.app.put()
: Defines a route for the PUT method.app.delete()
: Defines a route for the DELETE method.Let’s define routes for GET and POST methods:
app.get('/hello', (req, res) => {
res.send('Hello from GET route!');
});
app.post('/hello', (req, res) => {
res.send('Hello from POST route!');
});
http://localhost:3000/hello
will display “Hello from GET route!”.http://localhost:3000/hello
(e.g., using Postman) will display “Hello from POST route!”.Route parameters are named URL segments that capture values at specific positions in the URL.
app.get('/users/:userId', (req, res) => {
const userId = req.params.userId;
res.send(`User ID: ${userId}`);
});
Navigating to http://localhost:3000/users/123
will display “User ID: 123”.
Query parameters are URL segments that capture values at specific positions in the URL after the ?
.
app.get('/search', (req, res) => {
const query = req.query.q;
res.send(`Search query: ${query}`);
});
Navigating to http://localhost:3000/search?q=express
will display “Search query: express”.
Express allows you to handle different HTTP methods for the same route.
app.route('/book')
.get((req, res) => {
res.send('Get a book');
})
.post((req, res) => {
res.send('Add a book');
})
.put((req, res) => {
res.send('Update the book');
});
GET /book
will display “Get a book”.POST /book
will display “Add a book”.PUT /book
will display “Update the book”.Middleware functions are functions that have access to the request object (req
), the response object (res
), and the next middleware function in the application’s request-response cycle. They can execute code, modify the request and response objects, end the request-response cycle, and call the next middleware function.
app.use((req, res, next) => {
console.log('Time:', Date.now());
next();
});
app.get('/', (req, res) => {
res.send('Middleware example');
});
Each request to the root URL will log the current timestamp to the console.
You can create nested routes using Express Router.
const router = express.Router();
router.get('/info', (req, res) => {
res.send('User Info');
});
app.use('/users', router);
Navigating to http://localhost:3000/users/info
will display “User Info”.
Route groups allow you to apply middleware to a group of routes.
const router = express.Router();
router.use((req, res, next) => {
console.log('User Middleware');
next();
});
router.get('/profile', (req, res) => {
res.send('User Profile');
});
app.use('/users', router);
Each request to /users/profile
will log “User Middleware” to the console.
Express has built-in error-handling middleware functions.
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
If an error occurs, “Something broke!” will be sent as the response.
Express.js routing is a powerful feature that allows developers to define how an application responds to client requests at different endpoints. With the ability to handle various HTTP methods, utilize route and query parameters, and implement middleware, Express.js offers a robust and flexible solution for building web applications. Understanding these concepts is crucial for developing efficient and scalable Node.js applications.Happy coding !❤️