Untitled
unknown
javascript
a year ago
823 B
8
Indexable
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');
});Editor is loading...
Leave a Comment