- Let's create a complete example of an application-level middleware in an Express.js application. In this example, we'll create middleware that logs information about incoming requests.
- Project Structure: Create a project structure with the following directories and files:
- my-express-app/
- middlewares/
- requestLogger.js
- routes/
- index.js
- app.js
- package.json
- Middleware File (`requestLogger.js`): Create an application-level middleware that logs information about incoming requests:
// middlewares/requestLogger.js
const requestLogger = (req, res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
next(); // Call the next middleware in the stack
};
module.exports = requestLogger;
- Route File (`index.js`): Create a route file in the `routes` directory:
// routes/index.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('Hello from the index route!');
});
module.exports = router;
- Express App (`app.js`): Set up the Express.js application and use the application-level middleware:
// app.js
const express = require('express');
const requestLogger = require('./middlewares/requestLogger');
const indexRoute = require('./routes/index');
const app = express();
const PORT = 3000;
// Use the application-level middleware for all routes
app.use(requestLogger);
// Use the index route
app.use('/', indexRoute);
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
- Run the Application: Run your application using the command:
node app.js
- Visit `http://localhost:3000` in your browser. In the console where you started the server, you should see log entries with information about incoming requests, including the timestamp, HTTP method, and URL.
- This example demonstrates the use of an application-level middleware (`requestLogger`) in an Express.js application. The middleware logs information about incoming requests for all routes, providing a centralized way to capture request details before they reach the route handlers.
No comments:
Post a Comment