监听JavaScript中新网络请求:Axios请求无法触发自定义事件的问题
监听JavaScript中新网络请求:Axios请求无法触发自定义事件的问题
嘿,我来帮你捋清楚这个问题~
你现在的代码只拦截了浏览器的fetch API,但Axios在浏览器环境下默认是用XMLHttpRequest(简称XHR)来发送请求的,根本不会走fetch,所以你的Proxy自然抓不到Axios的请求啦。
给你两种解决思路,按需选择:
1. 同时拦截fetch和XMLHttpRequest(覆盖所有网络请求)
如果想监听所有类型的网络请求,除了已经写的fetch拦截,还要给XMLHttpRequest也加一层拦截。比如这样:
// 保留你原来的fetch拦截代码 window.fetch = new Proxy(window.fetch, { apply(actualFetch, that, args) { const result = Reflect.apply(actualFetch, that, args); result.then(() => { if (args.some(i => { return (typeof i === 'string' && i?.includes('/example')); })) { console.log('hello from fetch'); // 也可以派发自定义事件供其他地方监听 window.dispatchEvent(new CustomEvent('networkRequest', { detail: { url: args[0] } })); } }); return result; } }); // 新增XMLHttpRequest拦截,覆盖Axios这类用XHR的请求 const originalXHR = XMLHttpRequest; window.XMLHttpRequest = function() { const xhr = new originalXHR(); // 拦截open方法,存下请求URL const originalOpen = xhr.open; xhr.open = function(method, url) { this._requestUrl = url; return originalOpen.call(this, method, url); }; // 拦截send方法,判断URL并触发事件 const originalSend = xhr.send; xhr.send = function(body) { if (this._requestUrl?.includes('/example')) { console.log('hello from XHR/Axios'); window.dispatchEvent(new CustomEvent('networkRequest', { detail: { url: this._requestUrl } })); } return originalSend.call(this, body); }; return xhr; };
2. 直接用Axios拦截器(精准针对Axios请求)
如果你只需要监听Axios的请求,而且能访问到项目里的Axios实例,那用Axios自带的拦截器会更简单可靠,不用去改全局的XHR:
// 如果是全局的Axios实例 axios.interceptors.request.use( function(config) { // 在请求发送前判断URL if (config.url?.includes('/example')) { console.log('hello from Axios interceptor'); // 同样可以派发自定义事件 window.dispatchEvent(new CustomEvent('networkRequest', { detail: config })); } return config; }, function(error) { // 处理请求错误 return Promise.reject(error); } ); // 如果是你自己创建的Axios实例,就用实例来加拦截器 // const instance = axios.create({ baseURL: '/api' }); // instance.interceptors.request.use(...)
这样不管是fetch还是Axios的请求,只要URL包含/example,都能触发你想要的事件啦~
备注:内容来源于stack exchange,提问作者Abid Hasan
相关产品推荐
相关产品推荐

