axio深入实例以及配置

定义实例instance,使用实例

let instance = new axios.create({
	baseURL:”http:localhost:8080“,
	timeOut:1000
})
instance.get('/data.json').then(res=>{console.log(res)})

axios配置项

axios.create({
	baseURL:"" ,//请求域名,基本地址
	timeOut:"",  //请求超时时间
	url:"", //请求路径
	pa'ramsL:"", //请求参数拼接在url上
	method:"", //请求方法:get,post,put,patch,delete
	data:"",  //请求参数放在请求体
	headers:{
		token:""
	} //请求头
})

axios全局配置

axios.defaults.baseURL = "http://localhost:8080";
axios.defaults.timeOut = 1000

axios实例配置

let instance = new axios.create({
	baseURL:”http:localhost:8080“,
	timeOut:1000
})

axios请求配置

axios.get('./data.json',{
	timeOut:2000
})

优先级:全局配置<实例配置<请求配置

拦截器:包括请求拦截,响应拦截,取消拦截器;

//请求拦截器
axios.interceptors.request.use(config=>{
	//发送请求前做什么
	return config
},err=>{
  //请求错误时做什么
	return Promise.reject(err)
})
//响应拦截器
axios.interceptors.response.use(res=>{
 //响应成功对响应数据的处理
	return res
},err=>{
//响应错误时做什么
	return Promise.reject(err)
})
//取消拦截器
axios.interceptors.request.use(config=>{
	config.headers={
		auth:trun
	}
	return config
})
//实例 登录接口
let instance = new axios.create()
instance.interceptors.request.use(config=>{
	config.headers.token=""
	return config
})
instance.get("/get").then(res=>{console.log(res)}).cathc(err=>{console.log(err)});
//不需要登录
let instance2 = new axios.create();
instance2.get("/get").then(res=>{console.log(res)}).catch(err=>{console.log(err)})

取消请求

let source = axios.Canceltoken.source()
axios.get("/get",{
	cancelToken = source.token
}).then(res=>{
	console.log(res)
}).catch(err=>{
	console.log(err)
})
//取消请求
source.cancel("cancel http")

错误处理 实际开发中一般统一添加错误处理

let instance = new axios.create({})
    instance.get("/get").then(res=>{
        console.log(res)
    })
    instance.get("/get2").then(res=>{
        console.log(res)
    })
    instance.interceptors.request.use(config=>{
        return config
    },err=>{
        //请求http错误代码 401(请求超时) 400(未找到)
        $("#popup").show()
        setTimeout(() => {
            $("#popup").hide()
        }, 1000);
        return promise.reject(err)
    })
    instance.interceptors.response.use(res=>{
        return res
    },err=>{
        $("#popup").show()
        setTimeout(() => {
            $("#popup").hide()
        }, 1000);
        //响应http错误代码500(服务器错误) 502(重启)
        return Promise.reject(err)
    })
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

长影缚苍龙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值