So we installed NodeJS on our machine.
We also learned how to create a simple server using express.
Now we want to learn how to add additional middleware to our express server.
index.js
:touch index.js
const express = require("express");
const app = express();
const PORT = 8080;
app.get("/", (request, response) => {
response.send("Hello World");
});
app.listen(PORT, () => {
console.log(`Server running at: http://localhost:${PORT}/`);
});
Note: This is our starting point, we have one working route.
I updated req
to request
& res
to response
to increase readability.
What is Middleware?
Sometimes you want to add additional functionality between the default request-response-cycle. Let’s say you want to get some detailed information about the current request.
You can write a simple middleware, that handles this task, and add it to your express app.
logger.js
:touch logger.js
const logger = (req, res, next) => {
console.log(
`Time: ${new Date()} - Method: ${req.method} - Path: ${req.originalUrl}`
);
next();
};
module.exports = logger;
// import express (after npm install express)
const express = require("express");
// import the logger
const logger = require("./logger");
// create new express app and save it as app
const app = express();
// server configuration
const PORT = 8080;
// use the middleware
app.use(logger);
// create a route for the app
app.get("/", (req, res) => {
res.send("Hello World");
});
// make the server listen to requests
app.listen(PORT, () => {
console.log(`Server running at: http://localhost:${PORT}/`);
});
node index.js
Server running at: http://localhost:8080/
Time: Tue Sep 03 2019 17:32:30 GMT+0200 (Central European Summer Time) - Method: GET - Path: /
Hi! I'm Michael 👋 I'm a Mentor & Senior Web Developer - I help you to reach your (career) goals.