Express
Express
1. Write a route to handle a GET request to /welcome and send the response
"Welcome to Express!".
javascript
CopyEdit
app.get('/welcome', (req, res) => {
res.send('Welcome to Express!');
});
2. Write a dynamic route that extracts a userId from the URL /user/:id and sends it
back in the response.
javascript
CopyEdit
app.get('/user/:id', (req, res) => {
const userId = req.params.id;
res.send(`User ID: ${userId}`);
});
3. Create middleware that logs the requested URL and then passes control to the next
middleware.
javascript
CopyEdit
app.use((req, res, next) => {
console.log(`Request URL: ${req.url}`);
next();
});
4. Write a route to handle a POST request to /submit and respond with "Data
received".
javascript
CopyEdit
app.post('/submit', (req, res) => {
res.send('Data received');
});
javascript
CopyEdit
app.use((req, res, next) => {
if (req.query.auth !== 'true') {
res.status(401).send('Unauthorized');
} else {
next();
}
});