In Express.js, handling HTTP requests is a fundamental aspect of building web applications. Express provides a simple and intuitive way to handle incoming requests.
Here's an overview of handling requests in Express:
The req object represents the HTTP request and contains information about the request, such as parameters, query strings, headers, and more.
app.get('/user', (req, res) => { const userId = req.query.id; res.send(`User ID: ${userId}`); });
app.get('/user/:id', (req, res) => { const userId = req.params.id; res.send(`User ID: ${userId}`); });
app.get('/headers', (req, res) => { const userAgent = req.get('User-Agent'); const accept = req.get('accept'); console.log(`User-Agent: ${userAgent}, accept: ${accept} `) res.send(`User-Agent: ${userAgent}, accept: ${accept} `); });
const express = require('express'); const app = express(); const PORT = process.env.PORT || 3000; app.get('/', (req, res) => { res.send('Hello World!, Express.js'); }); app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
"app.get" is used to define a route for handling HTTP GET requests on the root URL ("/"). The callback function takes req (request) and res (response) as parameters.
const express = require('express'); const app = express(); const PORT = process.env.PORT || 3000; app.post('/add-user', (req, res) => { const {body} = req; console.log("Print Body", body); res.send('Add User Request Received'); }); app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
"app.post" is used to define a route for handling HTTP POST requests on the URL ("/add-user"). The callback function takes req (request) and res (response) as parameters.
const express = require('express'); const app = express(); const PORT = process.env.PORT || 3000; app.put('/update-user', (req, res) => { const {body} = req; console.log("Print Body", body); res.send('Update User Request Received'); }); app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
"app.put" is used to define a route for handling HTTP PUT requests on the URL ("/update-user"). The callback function takes req (request) and res (response) as parameters.
const express = require('express'); const app = express(); const PORT = process.env.PORT || 3000; app.delete('/delete-user', (req, res) => { const {userId} = req.query; console.log("Print UserId", userId); res.send('delete User Request Received'); }); app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
"app.delete" is used to define a route for handling HTTP DELETE requests on the URL ("/delete-user"). The callback function takes req (request) and res (response) as parameters.
// navigate to folder location where server.js exist node server.js