javascript - 如何通过 javascript 拦截所有 AJAX(xhr 和 fetch) 请求?
问题描述
我有 xhr 并获取要拦截的 xhr 请求和响应类型。
获取 API 调用
我试过了
window.fetch = function() {
// Intercept the request here
}
和
XMLHttpRequest.prototype.send = function() {
// Intercept the request here
}
但我想编写一个通用函数来拦截所有 xhr 请求和响应。
解决方案
默认情况下, fetch() 不提供拦截请求的方法,但想出一个解决方法并不难。您可以覆盖全局 fetch 方法并定义自己的拦截器,如下所示:
fetch = (originalFetch => {
return (...arguments) => {
const result = originalFetch.apply(this, arguments);
return result.then(console.log('Request was sent'));
};
})(fetch);
fetch('https://api.github.com/orgs/axios')
.then(response => response.json())
.then(data => {
console.log(data)
});
`
推荐阅读
- javascript - 类型错误
javascript错误 - javascript - 为什么它从这个 redux 调度返回 undefined ?
- docker - docker 检查挂载文件系统上的更改
- python - pyFMI Modelica:FMU 不包含此平台的二进制文件
- python - 检查目录及其子目录并打印路径
- latex - 转到乳胶表格单元格中的行
- android - 在 ImageView 中的触摸位置添加标记的最佳方法(类似于谷歌地图)
- javascript - 在模式对话框中设置默认值
- node.js - Nginx 和 node.js 的区别
- reactjs - 在 React JS redux 中一起使用 compose() 和 connect()