通过为 fetch 请求挂载全局拦截器并配合自定义属性实现接口请求结果追踪。具体做法是重写 window.fetch,在 promise 链中捕获成功与失败状态,利用 performance.mark 记录时间戳,并将耗时、url 及状态码存入数组或上报至监控服务。若需区分不同业务模块的请求,可在调用时传入唯一的 traceid 标识。

如何获取单个请求的完整生命周期数据
使用 performance.getEntriesByType('resource') 结合 fetch 返回的 Response 对象可以获取详细指标。核心逻辑是在请求发起前标记开始时间,响应结束后计算差值,同时提取 HTTP 状态码和最终重定向后的 URL。这种方法能准确反映网络层到应用层的实际耗时。

const originalFetch = window.fetch;
window.fetch = async function(url, options) {
const startMark = `fetch-start-${Date.now()}`;
performance.mark(startMark);
try {
const response = await originalFetch.apply(this, arguments);
const endMark = `fetch-end-${Date.now()}`;
performance.mark(endMark);
performance.measure(`fetch-measure-${url}`, startMark, endMark);
// 模拟上报逻辑
console.log({
url: response.url,
status: response.status,
time: performance.getEntriesByName(`fetch-measure-${url}`)[0].duration
});
return response;
} catch (error) {
console.error('Request failed:', error);
throw error;
}
};
// 测试调用
fetch('/api/data');
如何处理并发请求下的数据隔离问题
当多个请求并发执行时,必须确保每个请求的追踪数据互不干扰。解决方案是为每次调用生成独立的上下文对象,将 traceId 注入到 options.headers 或 body 中,并在拦截器内部通过闭包或 Map 结构存储该次请求的临时状态。这样即使请求乱序返回,也能根据 ID 正确关联结果。

const requestContexts = new Map();
window.fetch = async function(url, options = {}) {
const traceId = Math.random().toString(36).substr(2, 9);
const context = { id: traceId, startTime: Date.now(), url };
requestContexts.set(traceId, context);
// 可选:将 traceId 传递给后端
if (!options.headers) options.headers = {};
options.headers['X-Trace-ID'] = traceId;
try {
const response = await originalFetch.call(this, url, options);
context.endTime = Date.now();
context.status = response.status;
// 清理上下文
requestContexts.delete(traceId);
return response;
} catch (error) {
context.error = error.message;
requestContexts.delete(traceId);
throw error;
}
};
// 并发测试
Promise.all([
fetch('/api/a'),
fetch('/api/b')
]);
基于特定错误类型如何实现重试策略
针对网络超时或 5xx 服务端错误,可以在拦截器中判断 response.ok 或异常类型,若符合条件则触发指数退避重试。需要限制最大重试次数以防止死循环,并在每次重试前更新追踪数据中的重试计数。这种策略能有效提升弱网环境下的接口成功率。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!











