模仿axios实现自定义网络请求拦截器,支持微信小程序拦截,ajax拦截,支付宝小程序等

网友投稿 750 2022-10-11

模仿axios实现自定义网络请求-,支持微信小程序拦截,ajax拦截,支付宝小程序等

模仿axios实现自定义网络请求-,支持微信小程序拦截,ajax拦截,支付宝小程序等

http-interceptor

模仿axios实现自定义网络请求-,支持微信小程序拦截,ajax拦截,支付宝小程序等等

Usage

npm installnpm run build

Commonjs usage

const axios = require('./dist/index.js');

Browser

const axios = new Axios({ // defaults 公共请求参数可选 defaults: { }, // dispatchRequest 自定义请求必传 dispatchRequest (params) { }})axios.request(params).then().catch()

Interceptors

You can intercept requests or responses before they are handled by then or catch.

// Add a request interceptoraxios.interceptors.request.use(function (config) { // Do something before request is sent return config; }, function (error) { // Do something with request error return Promise.reject(error); });// Add a response interceptoraxios.interceptors.response.use(function (response) { // Any status code that lie within the range of 2xx cause this function to trigger // Do something with response data return response; }, function (error) { // Any status codes that falls outside the range of 2xx cause this function to trigger // Do something with response error return Promise.reject(error); });

Example

npm start

const axios = new Axios({ defaults: { common: 123 }, dispatchRequest (params) { return new Promise((resolve, reject) => { $.ajax('http://liuweibo-:7654/api/getBlog?type=all&num=1&pageNum=10&wd=', { success: function (res) { resolve(res) }, fail: function (err) { reject(err) } }) }); } }) axios.interceptors.request.use(function (config) { // Do something before request is sent console.log('request') return config; }, function (error) { // Do something with request error return Promise.reject(error); }); // Add a response interceptor axios.interceptors.response.use(function (response) { console.log('response') // Any status code that lie within the range of 2xx cause this function to trigger // Do something with response data return response; }, function (error) { // Any status codes that falls outside the range of 2xx cause this function to trigger // Do something with response error return Promise.reject(error); }); axios.request({ b: '222' }).then( res => { console.log(res) }).catch(err => { console.log('err', err) })

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:spark streaming 文件系统
下一篇:tensorflow 梯度下降
相关文章

 发表评论

暂时没有评论,来抢沙发吧~