Intro
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.
Reuse our simple server from the last article
- Open your terminal
- Create a file named
index.js
:
touch index.js
- Add this JavaScript code into it:
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.
Additional Middleware
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.
Create a Middleware
- Create a file named
logger.js
:
touch logger.js
- Add this JavaScript code into it:
const logger = (req, res, next) => {
console.log(
`Time: ${new Date()} - Method: ${req.method} - Path: ${req.originalUrl}`
);
next();
};
module.exports = logger;
- Require the new logger in index.js and use the middleware:
// 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}/`);
});
Run it from the terminal
- Run it:
node index.js
-
Visit: http://localhost:8080
-
Console Result:
Server running at: http://localhost:8080/
Time: Tue Sep 03 2019 17:32:30 GMT+0200 (Central European Summer Time) - Method: GET - Path: /
Further Reading
Questions
- What's your favorite middleware for express?