const express = require('express');
const app = express();
const port = 8080;
// Route with URL parameters
app.get('/users/:userId', (req, res) => {
res.send(`User profile for ID: ${req.params.userId}`);
});
// Route with multiple parameters
app.get('/users/:userId/posts/:postId', (req, res) => {
res.send(`
<h2>User and Post Information</h2>
<p>User ID: ${req.params.userId}</p>
<p>Post ID: ${req.params.postId}</p>
`);
});
// Optional parameters using ?
app.get('/products/:category/:product?', (req, res) => {
if (req.params.product) {
res.send(`Viewing product ${req.params.product} in category ${req.params.category}`);
} else {
res.send(`Viewing all products in category ${req.params.category}`);
}
});
// Parameter with pattern (only digits)
app.get('/items/:itemId(\\d+)', (req, res) => {
res.send(`Item ID must be numeric: ${req.params.itemId}`);
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});