Scenario:
You want to add middleware to your Express application to log each incoming request with the current timestamp.
Solution:
- First, let’s create a new file named
middleware.js
in theroutes
directory. - In the
middleware.js
file, write the following code:
const morgan = require('morgan');
module.exports = function requestLogger(req, res, next) {
const logEntry = `[${new Date().toISOString()}] ${req.method} ${req.url}`;
console.log(logEntry);
next();
};
- Import the new middleware in
app.js
:
const requestLogger = require('./routes/middleware');
- Use the middleware in the
app.js
file:
app.use(requestLogger);
- Now, the incoming requests will be logged with the current timestamp before being processed by any other middleware or routes.
Tests:
- Start the application by running
npm start
in the terminal. - Use a tool like Postman or curl to send requests to the application.
- Check the console output for the logged requests.
Expected Output:
[2023-03-28T14:30:12.000Z] GET /
[2023-03-28T14:30:12.001Z] GET /favicon.ico
[2023-03-28T14:30:12.002Z] GET /stylesheets/style.css
These tests should verify that the custom middleware is correctly logging incoming requests with the current timestamp.