拦截所有的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.use((req, res, next) => {
if (!req.headers.datetime) {
res.send("请求头中缺少请求发起时间!")
return
}
next();
})
// 设置路由规则
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");
});