代码拉取完成,页面将自动刷新
一个用于拦截ajax
和fetch
的请求和响应的小工具.
我自己已将它用在了我的chrome浏览器扩展插件项目中, 但你也可以将其用于其他很多地方,例如数据采集、API的mock,甚至是用于多个系统的单点登陆(SSO)。
请注意,ajax部分完全基于wendux
的源代码: https://github.com/wendux/Ajax-hook
,因为这个轮子已经很完美了。
安装
下载这个git仓库。
运行 npm run build
拦截ajax, 需要使用dist
目录下的ajaxhook.ming.js
.
<script src="dist/ajaxhook.min.js"></script>
拦截fetch需要使用dist
下的fetchhook.ming.js
.
<script src="dist/ajaxhook.min.js"></script>
使用
用proxy
拦截ajax:
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:
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。 尽情使用吧,因为我让它以 许可发行.
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。