Home > Web Front-end > JS Tutorial > body text

A brief discussion on how to use Nodejs to create access logging middleware

青灯夜游
Release: 2021-09-18 10:38:08
forward
1795 people have browsed it

This article will share with you how to use node.js to implement the interface access logging function. I hope it will be helpful to everyone!

A brief discussion on how to use Nodejs to create access logging middleware

Middleware-Access Log

Target

Use middleware technology to write a middleware for recording access logs

Middleware

middleware, middleware is A special url address processing function , which is used as a parameter of app.use (middleware function) or used in a routing processing function.

  • Middleware is the biggest feature of express and the most important design. Express is a web development framework with minimalist functions. It is completely composed of routing and middleware: in essence, an Express application is calling various middleware. [Recommended learning: "nodejs tutorial"]
  • An express application is completed by many middlewares.

A brief discussion on how to use Nodejs to create access logging middleware

Basic use of middleware

// 具名函数格式:
const handler1 = (req, res, next) => {
  console.log(Date.now());
  next();
}
app.use(handler1);
Copy after login
// 匿名函数格式:
app.use((req, res, next) => {
  console.log(Date.now());
  next();
});
Copy after login

Description: Middleware function There are three basic parameters in it, req, res, next

  • req is the request-related object, which is related to the next middleware function The req object is an object

  • res which is the response-related object. It is the same object as the res object in the next middleware function

  • next It is a function. Calling it will jump out of the current middleware function and execute subsequent middleware; if next is not called or res.end is not executed, the entire request will be stuck in the current middleware.

Ideas

    ##Apply middleware technology to record each request
  • Create a
  • .json file to store records
  • Read the data and put it into the
  • .json file

js implementation code

const express = require("express");
const app = express();
const fs = require("fs");
// 获取ip的函数
function getClientIp(req) {
  return (
    req.headers["x-forwarded-for"] ||
    req.connection.remoteAddress ||
    req.socket.remoteAddress ||
    req.connection.socket.remoteAddress
  );
}
// 中间件
app.use((req, res, next) => {
  console.log("时间", new Date());
  console.log("访问地址", req.url);
  console.log("f访问ip", getClientIp(req));
  /**
   * 建立一个.json的文件 []
   * 获取文件内容'[]'==>[]
   * let obj = {time:xxx,url:xxx,ip:xxx}
   * [].push(obj)
   * [].push(obj)覆盖写入.json的文件
   */
  fs.readFile("hhhh.json", "utf8", (err, data) => {
    if (err) {
      console.log("文件读取错误", err);
      return;
    }
    let arr = JSON.parse(data);
    //console.log(arr);
    let obj = {};
    obj.time = new Date();
    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("写入错误", err);
      }
    });
  });
  next();
});
// 监听接口
app.listen(8080, () => {
  console.log("成功,接口是8080");
});
Copy after login

Console screenshot

A brief discussion on how to use Nodejs to create access logging middleware

Original address: https://juejin.cn/post/7008510822578126862


Author: Not cowardly

For more programming-related knowledge, please Visit:

Programming Video! !

The above is the detailed content of A brief discussion on how to use Nodejs to create access logging middleware. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template