Untitled
unknown
javascript
a month ago
823 B
2
Indexable
Never
const logRequest = (req, res, next) => { // Extracting details from the request const logDetails = { endpoint: req.originalUrl, method: req.method, ip: req.ip, timestamp: new Date() }; // Log the details to MongoDB db.collection('requestLogs').insertOne(logDetails, (err) => { if (err) { console.error('Error logging request:', err); } }); // Call the next middleware or route handler next(); }; // Usage in the Express app const express = require('express'); const app = express(); // Middleware should be placed before route handlers app.use(logRequest); // Example route handler app.get('/', (req, res) => { res.send('Hello, World!'); }); app.listen(3000, () => { console.log('Server is running on port 3000'); });
Leave a Comment