nodejs的express使用全局拦截器保存用户请求和响应日志

前言:为了记录用户的请求记录,想要记录用户的ip,请求入参,请求方法,以及返回内容,我使用中间件收集用户请求数据保存到数据库

1.数据库表结构

CREATE TABLE `admin_request_log` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
  `user_id` int(11) DEFAULT NULL COMMENT '用户id',
  `url` varchar(1000) DEFAULT NULL COMMENT '请求地址',
  `method` varchar(10) DEFAULT NULL COMMENT '请求方式',
  `body` text COMMENT '请求body',
  `params` varchar(1000) DEFAULT NULL COMMENT '请求params',
  `ip_address` varchar(100) DEFAULT NULL COMMENT 'ip地址',
  `result` text COMMENT '响应内容',
  `created_time` datetime DEFAULT NULL COMMENT '创建时间',
  `updated_time` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=89 DEFAULT CHARSET=utf8mb4;

2.日志拦截器的方法

// 全局日志拦截器
const endMiddleware = (req, res, next) => {
  const defaultWrite = res.write;
  const defaultEnd = res.end;
  const chunks = [];
  res.write = (...restArgs) => {
    chunks.push(Buffer.from(restArgs[0]));
    defaultWrite.apply(res, restArgs);
  };
  res.end = (...restArgs) => {
    let mList = ["POST","GET"]
    if(mList.indexOf(req.method) !== -1){
      if (restArgs[0]) {
        chunks.push(Buffer.from(restArgs[0]));
      }
      const body = Buffer.concat(chunks).toString('utf8');
      const time = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
      AdminRequestLog.create({
        user_id: (req.data && req.data.user_id) ? req.data.user_id : null,
        url:req.url,
        method: req.method,
        body: JSON.stringify(req.body),
        params: "",
        ip_address: getClientIp(req),
        result: JSON.stringify(body),
        create_time: time,
        updated_time: time,
      });
    }
    defaultEnd.apply(res, restArgs);
  };
  next();
};

app.use(endMiddleware)

使用的是res.end方法等待方法返回,然后将返回数据解析出来保存到数据库

3.缺省方法说明
(1)AdminRequestLog 这个是使用的数据库orm框架sequelize模型插入数据

(2)getClientIp 这和是获取用户ip的方法,如下:

//函数返回ip地址
 function getClientIp(req) {
     return req.headers['x-forwarded-for'] ||
         req.connection.remoteAddress ||
         req.socket.remoteAddress ||
         req.connection.socket.remoteAddress;
 }

4.最终效果
在这里插入图片描述

Node.js使用axios请求接口以及拦截器使用方法如下: 首先,需要安装axios模块: ``` npm install axios ``` 然后,在代码中引入axios模块: ```js const axios = require('axios'); ``` 接下来,可以使用axios发送GET、POST等请求: ```js axios.get('http://example.com/api') .then(response => { console.log(response.data); }) .catch(error => { console.log(error); }); axios.post('http://example.com/api', {data: 'hello'}) .then(response => { console.log(response.data); }) .catch(error => { console.log(error); }); ``` 当然,axios还支持一些其他的请求方法,比如PUT、DELETE等。 接下来,我们可以使用axios的拦截器请求响应进行处理。例如,我们可以在请求头中添加token: ```js axios.interceptors.request.use(config => { const token = localStorage.getItem('token'); if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; }, error => { return Promise.reject(error); }); ``` 在上面的代码中,我们使用了axios的interceptors.request.use方法,它可以在请求被发送出去之前对其进行拦截处理。在这个例子中,我们将localStorage中存储的token添加到请求头中的Authorization字段中。 我们还可以使用axios的interceptors.response.use方法对响应进行处理。例如,我们可以检查响应状态码是否为401,如果是,则跳转到登录页面: ```js axios.interceptors.response.use(response => { return response; }, error => { if (error.response.status === 401) { window.location.href = '/login'; } return Promise.reject(error); }); ``` 在上面的代码中,我们使用了axios的interceptors.response.use方法,它可以在响应被接收之前对其进行拦截处理。在这个例子中,我们检查了响应状态码是否为401,并且在这种情况下跳转到登录页面。 以上就是在Node.js使用axios请求接口及拦截器使用方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值