# ajax_fetch_interceptor
**Repository Path**: hokhyk/ajax_fetch_interceptor
## Basic Information
- **Project Name**: ajax_fetch_interceptor
- **Description**: A simple javascript tool used to intercept `ajax` as well as `fetch` requests and responses.
I myself use it in my chrome plugin project, but you can use it in many other places like `data collection`, `api mocking`, and even `SSO` of multiple systems.
Please note ajax part is completely based on `wendux`'s source code at `https://github.com/wendux/Ajax-hook` as it is already a splendid wheel.
- **Primary Language**: JavaScript
- **License**: MIT
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 12
- **Forks**: 6
- **Created**: 2021-03-28
- **Last Updated**: 2025-02-06
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# ajax-fetch-interceptor
## 介绍
一个用于拦截`ajax`和`fetch`的请求和响应的小工具.
我自己已将它用在了我的chrome浏览器扩展插件项目中, 但你也可以将其用于其他很多地方,例如数据采集、API的mock,甚至是用于多个系统的单点登陆(SSO)。
请注意,ajax部分完全基于`wendux`的源代码: `https://github.com/wendux/Ajax-hook`,因为这个轮子已经很完美了。
## 使用方法
1. 安装
- 下载这个git仓库。
- 运行 `npm run build`
- 拦截ajax, 需要使用`dist`目录下的`ajaxhook.ming.js`.
```html
```
- 拦截fetch需要使用`dist`下的`fetchhook.ming.js`.
```html
```
2. 使用
- 用`proxy`拦截ajax:
```javascript
ah.proxy({
//请求发起前进入
onRequest: (config, handler) => {
console.log(config.url)
handler.next(config);
},
//请求成功后进入
onResponse: (response, handler) => {
console.log(response.response)
handler.next(response)
},
//请求发生错误时进入,比如超时;注意,不包括http状态码错误,如404仍然会认为请求成功
onError: (err, handler) => {
console.log(err.type)
handler.next(err)
}
})
```
- 用`hookFetch`拦截fetch:
```javascript
fh.hookFetch({
requestInterceptors: {
// input is usually url, init is of Request entity.
itc1: function (input, init)
{ .... do something
return init },
itc2: function (input, init)
{ .... do something
return init },
},
responseInterceptors: {
// input is usually url, interceptorRes is of Response body.
itc3: function (input, interceptorRes)
{ .... do something
return interceptorRes },
itc4: function (input, interceptorRes)
{ .... do something
return interceptorRes },
}
})
```
从这里下载完整的仓库: https://gitee.com/hokhyk/ajax_fetch_proxy。
尽情使用吧,因为我让它以[](https://opensource.org/licenses/mit-license.php) 许可发行.