Middleware – Access logs

The target

Using middleware technology, write a middleware to record access logs

The middleware

Middleware, a special URL handler, is used as an argument to app.use(middleware function) or in a routing handler.

  • Middleware is the biggest feature of Express and one of its most important designs.Express is a web development framework that is minimalist in its own right, all about routing and middleware: essentially, an Express application is a call to middleware.
  • An Express application is made up of a lot of middleware.

Basic use of middleware

// Named function format:
const handler1 = (req, res, next) = > {
  console.log(Date.now());
  next();
}
app.use(handler1);
Copy the code
// Anonymous function format:
app.use((req, res, next) = > {
  console.log(Date.now());
  next();
});
Copy the code

Middleware function has three basic parameters, req, RES, next

  • The REQ is the request related object, which is the same object as the REQ object in the next middleware function

  • The RES is the response-related object, which is the same object as the RES object in the next middleware function

  • Next is a function that will jump out of the current middleware function and execute subsequent middleware; If next is not called and res.end is not executed, the entire request will get stuck in the current middleware.

Train of thought

  • Use middleware technology to log each request
  • To establish a.jsonIs used to store records
  • After the data is read into.jsonfile

Js implementation code

const express = require("express");
const app = express();
const fs = require("fs");
// Get the IP function
function getClientIp(req) {
  return (
    req.headers["x-forwarded-for"] ||
    req.connection.remoteAddress ||
    req.socket.remoteAddress ||
    req.connection.socket.remoteAddress
  );
}
/ / middleware
app.use((req, res, next) = > {
  console.log("Time".new Date());
  console.log("Access Address", req.url);
  console.log("F access IP", getClientIp(req));
  / * * * to create a json file [] * access to the file content '[]' = = > [] * let obj = {time: XXX, url: XXX, IP: XXX} * []. Push (obj) * []. Push (obj) write. Json file * /
  fs.readFile("hhhh.json"."utf8".(err, data) = > {
    if (err) {
      console.log("File read error", err);
      return;
    }
    let arr = JSON.parse(data);
    //console.log(arr);
    let obj = {};
    obj.time = new Date(a); obj.url = req.url; obj.ip = getClientIp(req); arr.push(obj);console.log(arr);
    let newArr = JSON.stringify(arr);
    fs.writeFile("hhhh.json", newArr, (err) = > {
      if (err) {
        console.log("Write error", err); }}); }); next(); });// Listen on the interface
app.listen(8080.() = > {
  console.log("Yes, the interface is 8080");
});

Copy the code

Console screenshot