Routing in Node.js refers to the process of 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, PUT, DELETE, etc.).
const express = require('express');
const app = express();
const PORT = 3000;
// Middleware to parse JSON requests
app.use(express.json());
// Simple route
app.get('/', (req, res) => {
res.send('Hello, World!');
});
// Route with parameters
app.get('/greet/:name', (req, res) => {
const name = req.params.name;
res.send(`Hello, ${name}!`);
});
// Route with query parameters
app.get('/user', (req, res) => {
const { id } = req.query;
res.send(`User ID: ${id}`);
});
// Route with POST method
app.post('/user', (req, res) => {
const { name, age } = req.body;
res.send(`User added: ${name}, ${age}`);
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
© www.thecoderjob.com. All Rights Reserved. Designed by HTML Codex