Node Routing
Introduction
Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on). In simple terms, Routing allows targeting different routes or different URLs on our page.
Routing in Node.js is a way to define how an application responds to client requests for different URLs (or endpoints) and HTTP methods such as GET, POST, PUT, DELETE, etc. It allows you to handle different operations for each endpoint by associating routes with specific handler functions.Setting Up Express
To understand the routing in node js you need to follow below steps,
First, you need to install Express,npm install express
create a basic Express application,
const express = require('express'); const app = express(); const port = 3000; app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); });
Basic Routing
A route in Express is a combination of a path and an HTTP method that defines how your application responds to a client request.// Respond with "Hello World" when a GET request is made to the homepage app.get('/', (req, res) => { res.send('Hello World'); }); // Respond with "About Page" when a GET request is made to /about app.get('/about', (req, res) => { res.send('About Page'); });
Route Methods
Express supports various HTTP methods such asget
,post
,put
,delete
, etc. Each method corresponds to a specific HTTP request.// Handle GET request app.get('/user', (req, res) => { res.send('GET request to the user'); }); // Handle POST request app.post('/user', (req, res) => { res.send('POST request to the user'); }); // Handle PUT request app.put('/user', (req, res) => { res.send('PUT request to the user'); }); // Handle DELETE request app.delete('/user', (req, res) => { res.send('DELETE request to the user'); });
Route Parameters
Route parameters are named URL segments used to capture values specified at their position in the URL.app.get('/users/:userId/books/:bookId', (req, res) => { res.send(req.params); });
If you visit
/users/123/books/456
, the response will be,{ "userId": "123", "bookId": "456" }
Query Parameters
Query parameters are used to filter or specify details in a URL query string.app.get('/search', (req, res) => { res.send(req.query); });
If you visit
/search?term=nodejs&sort=asc
, the response will be,{ "term": "nodejs", "sort": "asc" }
Middleware
Middleware functions can perform a variety of tasks like executing code, modifying the request and response objects, ending the request-response cycle, and calling the next middleware function.const myLogger = (req, res, next) => { console.log('LOGGED'); next(); }; app.use(myLogger); app.get('/', (req, res) => { res.send('Hello World'); });
Handling 404 Errors
To handle 404 errors (page not found), you can add a middleware function at the end of your routes.app.use((req, res, next) => { res.status(404).send("Sorry, can't find that!"); });
Chaining Route Handlers
Multiple callback functions can handle a route, making it easier to handle complex requests.app.get('/example', (req, res, next) => { console.log('First callback'); next(); }, (req, res) => { res.send('Second callback'); });
By understanding and utilizing these concepts, you can effectively manage routing in your Node.js applications with Express.
Building an API
i) Initialize a new Node.js project
This will create a new package.json file for your new project.npm init -y
ii) Install Express.js
Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications.npm install express
iii) Create the Server File
Create a new file namedindex.js
in your project directory.const express = require('express'); const app = express(); const port = 3000; // Middleware to parse JSON bodies app.use(express.json()); // Basic route app.get('/', (req, res) => { res.send('Hello, World!'); }); // Start the server app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); });
iv) Define API Endpoints
Add more routes to yourindex.js
file. For example, you can add routes to handle basic CRUD operations (Create, Read, Update, Delete)// Dummy data let items = [ { id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }, ]; // Get all items app.get('/api/items', (req, res) => { res.json(items); }); // Get item by id app.get('/api/items/:id', (req, res) => { const item = items.find(i => i.id === parseInt(req.params.id)); if (!item) return res.status(404).send('Item not found'); res.json(item); }); // Create new item app.post('/api/items', (req, res) => { const newItem = { id: items.length + 1, name: req.body.name }; items.push(newItem); res.status(201).json(newItem); }); // Update item app.put('/api/items/:id', (req, res) => { const item = items.find(i => i.id === parseInt(req.params.id)); if (!item) return res.status(404).send('Item not found'); item.name = req.body.name; res.json(item); }); // Delete item app.delete('/api/items/:id', (req, res) => { const itemIndex = items.findIndex(i => i.id === parseInt(req.params.id)); if (itemIndex === -1) return res.status(404).send('Item not found'); const deletedItem = items.splice(itemIndex, 1); res.json(deletedItem); });
v) Run the server and test the API
Open your browser or a tool like Postman.
Navigate tohttp://localhost:3000
to see the "Hello, World!" message.
Test other routes likehttp://localhost:3000/api/items
,http://localhost:3000/api/items/1
, etc.