axios的文档说明:axios

此处只记录部分,及对axios的封装

目录:

1、axios.create(config)
2、请求拦截和响应拦截
3、取消拦截
4、请求拦截和响应拦截的实践

axios.create(config)

1、根据指定的配置创建一个新的axios;
2、明明直接由axios()和axios.get()等方法,为什么还有设置create呢?

比如有个需求,项目中有部分接口需要配置的与另外的不一样,比如一个前端应用可以向多个后端应用发送请求,baseUrl就可以根据create设置不同的。

const instance = axios.create({
    baseUrl: 'http://location:3000'
})

// 请求
instance({
    url:/getUser/xxx'
})

请求拦截器和响应拦截器

请求拦截器传两个函数,成功函数需要返回config,失败函数返回Promise.reject(error)
响应拦截器传两个函数,成功函数需要返回response(结果),失败函数返回Promise.reject(error)
// 使用请求拦截器
axios.interceptors.request.use(config => {
    return config		// !!!返回config配置
}, error => {})
 
axios.interceptors.response.use(config => {
    response => {
        return response		// !!返回数据
    },
    error => {
       // 需要将请求错误继续向下传递
       // throw error    // 方法1
       return Promise.reject(error)   // 方法2
    }
})

// 移除拦截器
const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
可以设置多个拦截器,如果按顺序设置
拦截器顺序request1, request2,response1, response2
执行顺序:request2 ,request1, response1, response2

请求拦截器后添加先执行,响应拦截器先添加先执行
(为什么?后面源码解析哦)

取消请求

配置流程

1、配置cancalToken对象
2、缓存用于取消请求的cancel函数
3、在后面特定实际调用cancel函数取消请求
4、在错误回调中判断如果error是cancel,做响应处理

let cancel
// 发送请求
function getList(){
	axios({
	    url: 'http://localhost:9999',
	    cancelToken: new axios.CancelToken(c => {
	        cancel = c // c是函数,用于取消当前请求的函数
	    })
	}).then(response => {
	    // 不管成功失败,都要将cancel置空,此时的取消请求已经无效了 
	    cancel = null
	    consolg.log('请求1成功了', response.data)
	}, error => {
	    cancel = null
	    console.log('error', error)
	})
}

// 取消请求
function cancelReq () {
    // if (Object.prototype.toString.call(cancel) === "[object Function]")
    if(typeof cancel === 'function') {
        cancel() // 执行取消请求的函数
    } else {
        console.log('没有可取消的请求')
    }
}

发送请求,将前面未完成的请求取消

思路:去判断cancel是否为函数,是,则取消请求,继续发送请求2!!!无论请求成功失败,都要将cancel置空

function getList(){
	if (typeof cancel ===function') {
	    Cancel(‘取消前面的请求')
	}
	axios({
	    url: 'http://localhost:9999',
	    cancelToken: new axios.CancelToken(c => {
	        cancel = c // c是函数,用于取消当前请求的函数
	    })
	}).then(response => {
	    // 不管成功失败,都要将cancel置空,此时的取消请求已经无效了 
	    cancel = null
	    consolg.log('请求1成功了', response.data)
	}, error => {
	    cancel = null
	    console.log('error', error)
	})
}
👆这个代码有个问题:点击多次,第一次的请求是被取消了,但是第二次的请求没有被取消,

原因:点击发送请求1,请求的时候立马发送1的请求,
点击发送请求2,发现cancel是个函数, 那把cancel取消掉,这个取消导致请求1的error函数异步执行,被放到回调队列里
然后发送请求2,如果此时1的error里cancel = null, 会导致2设置cancel又为空,所以再点击请求的时候就取消不了前面的请求了
解决:

function getList(){
	axios({
	    url: 'http://localhost:9999',
	    cancelToken: new axios.CancelToken(c => {
	        cancel = c 
	    })
	}).then(response => {
	    cancel = null
	    consolg.log('请求1成功了', response.data)
	}, error => {
	    //!! error有可能是cancel类型, 请求如果被取消,这里是返回取消的message
	    if(axios.isCancel(error)) {	
	        console.log('取消请求失败', error.message)
	    } else {
	        cancel = null
	        console.log('请求失败', error.message)
	    }
	})
}

取消请求就先到这啦

请求拦截和响应拦截的实践

如果用上面代码去发送请求,每次请求都要写类似于getList, 代码量大,–> 请求拦截和响应拦截用
let cancel 
function getList1 () {
    axios({
        url: 'http://localhost:9999',
    }).then(response => {
        consolg.log('请求1成功了', response.data)
    }, error => {
        console.log('请求失败', error.message)
    })
}

// 使用请求拦截器
axios.interceptors.request.use(config => {
    if(typeof cancel === 'function') {
        cancel()    // 执行取消请求的函数
    }
    config.cancelToken = new axios.CancelToken(c => {
        cancel = c  //  c是函数,用于取消当前请求的函数
    })
    return config
}, error => {})
 
axios.interceptors.response.use(config => {
    response => {
        cancel = null   
        return response
    },
    error => {
        if(axios.isCancel(error)) {     // 取消请求的错误 
            console.log('取消请求失败', error.message)
            // 中断promise链
            return new Promise(() => {})
        } else {
            cancel = null   
            console.log('请求失败', error.message)
            // 需要将请求错误继续向下传递
            // throw error    // 方法1
            return Promise.reject(error)   // 方法2
        }
    }
})

function cancelReq () {
    // if (Object.prototype.toString.call(cancel) === "[object Function]")
    if(typeof cancel === 'function') {
        cancel()    // 执行取消请求的函数
    } else {
        console.log('没有可取消的请求')
    }
}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐