拦截所有的HTTP请求,强制添加请求头

拦截所有的HTTP请求,强制添加请求头

实现思路

不管是基于原生的XMLHttpRequest,还是利用Axios、Fetch、Ajax等各种,地层都需要调用XMLHttpRequest原型的send方法来发起请求,所以可以通过重写XMLHttpRequest的send方法实现

重写代码

window.onload = function () {
    const originalSendMethod = XMLHttpRequest.prototype.send;
    XMLHttpRequest.prototype.send = function (body) {
        //在请求头中强制添加请求发起时间
        this.setRequestHeader("dateTime", Date.now());
        originalSendMethod.apply(this, body);
    };

测试

客户端

const xhr = new XMLHttpRequest();
// GET请求
xhr.open("GET", "http://127.0.0.1:3000/");
// POST请求
// xhr.open("POST", "http://127.0.0.1:3000/");
xhr.send();
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
        alert(xhr.responseText);
    }
};

服务端

const express = require("express");
const util = require("util");
const cors = require("cors");

// 允许跨域
const app = express();
app.use(cors());

// 设置路由规则
app.get("/", (req, res) => {
	const reqTime = req.headers.datetime;
	const resTime = Date.now();
	const resContent = util.format(
		"GET请求发起时间为:%d,响应时间为:%d,请求用时:%d",
		reqTime,
		resTime,
		resTime - reqTime
	);
	res.send(resContent);
});

app.post("/", (req, res) => {
	const reqTime = req.headers.datetime;
	const resTime = Date.now();
	const resContent = util.format(
		"POST请求发起时间为:%d,响应时间为:%d,请求用时:%d",
		reqTime,
		resTime,
		resTime - reqTime
	);
	res.send(resContent);
});

app.listen(3000, () => {
	console.log("服务已启动,监听端口:3000");
});

结果

image-20240714130238444

d314df89a8f6798bb51fbf14ae83ff2

647500d07d430f50fbb0c8f6196b06b

相关推荐

  1. httphttps 所有请求信息

    2024-07-14 17:06:01       31 阅读
  2. curl获取http请求响应

    2024-07-14 17:06:01       26 阅读
  3. vue请求拦截统一给所有请求加loading

    2024-07-14 17:06:01       45 阅读
  4. http header 请求 x-forwarded-for

    2024-07-14 17:06:01       52 阅读
  5. HTTP协议——请求请求体详情

    2024-07-14 17:06:01       24 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-14 17:06:01       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-14 17:06:01       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-14 17:06:01       58 阅读
  4. Python语言-面向对象

    2024-07-14 17:06:01       69 阅读

热门阅读

  1. Python bisect的使用

    2024-07-14 17:06:01       25 阅读
  2. `nmap`模块是一个用于与Nmap安全扫描器交互的库

    2024-07-14 17:06:01       18 阅读
  3. 【EasyExcel】根据单元格内容自动调整列宽

    2024-07-14 17:06:01       19 阅读
  4. Redis 底层数据结构

    2024-07-14 17:06:01       21 阅读
  5. C# Static的一些理解

    2024-07-14 17:06:01       17 阅读
  6. 多线程编程中的条件变量及其优化

    2024-07-14 17:06:01       15 阅读
  7. STM32F103控制0.96寸OLED显示

    2024-07-14 17:06:01       15 阅读
  8. GESP C++ 三级真题(2023年9月)T1 ⼩ 杨储蓄

    2024-07-14 17:06:01       14 阅读
  9. 2024年交安安全员考试题库及答案

    2024-07-14 17:06:01       19 阅读
  10. 2024年高校辅导员考试题库及答案

    2024-07-14 17:06:01       25 阅读
  11. VMM、VMI、VIM的简介

    2024-07-14 17:06:01       16 阅读