全局使用 (推荐)
局部使用
const res = await req.ajax({
path: "https://www.easy-mock.com/mock/5ca6ec41215a7b66ff10343d/example/query",
})
1.简单使用
const res = await this.$req.ajax({
path: "example/query", //可以是完整路径也可以后半部分
})
console.log(res);
2.带请求提示
const res = await this.$req.ajax({
path: "example/query",
title: "正在加载", //false 则不显示
})
console.log(res);
3.带参数请求
4.单个请求带拦截
const res = await this.$req.ajax({
path: "example/query",
title: "正在加载",
data:{
name:'hhyang'
},
abortFun: (info,bt) => {
bt.abort();
},
})
console.log(res);
5.监听请求完成,无论失败还是成功。当然可以使用 then、catch、finally 详细
const res = await this.$req.ajax({
path: "example/query",
data:{
name:'hhyang'
},
finishFun:finsh => { //使用await 用此方法即可监听到
console.log(finsh)
}
})
console.log(res); //成功之后的返回,如要捕捉失败请使用try、catch
6.携带额外参数,不会上传。可提供给开发者分辨某个请求 详细
const res = await this.$req.ajax({
path: "example/query",
title: "正在加载",
data:{
name:'hhyang'
},'我是额外参数1','我是额外参数2')
console.log(res); //成功之后的返回,如要捕捉失败请使用try、catch
//或者这样
const res = await this.$req.ajax({
path: "example/query",
title: "正在加载",
data:{
name:'hhyang'
},
},{
parmas1:'我是额外参数1',
parmas2:'我是额外参数2',
})
console.log(res); //成功之后的返回,如要捕捉失败请使用try、catch
7.捕捉请求错误
8.自定义 header、dataType、responseType、type
const res = await this.$req.ajax({
path:"example/query",
type:"POST",
header:{
'content-type': 'application/x-www-form-urlencoded'
},
dataType: 'json',
responseType: 'text',
})
console.log(res);
9.设置全局请求前拦截
//延迟函数
let timeout=function(time=3000){
return new Promise(resolve=>{
setTimeout(()=>{
resolve();
},time)
})
//同步写法
req.defaultReq.beforeSend=res=>{
if(res.data.token!=''){ //验证token存在的情况下才放行
return res
}
}
//同步写法
req.defaultReq.beforeSend=res=>{
delete res.data; //删除传递的参数选项
return res; //返回新的请求参数
}
//异步写法
req.defaultReq.beforeSend=async res=>{
await timeout(); //3秒后执行删除,再返回
delete res.data; //删除传递的参数选项
return res; //返回新的请求参数
}
10.设置全局响应后拦截
//延迟函数
let timeout=function(time=3000){
return new Promise(resolve=>{
setTimeout(()=>{
resolve();
},time)
})
}
//同步写法
req.defaultReq.beforeFinish=res=>{
if(res.data.userOut){ //退出登录不返回数据,标记此次请求无效
uni.reLaunch({
url: 'login?userOut=true'
});
}else{
return res;
}
}
//同步写法
req.defaultReq.beforeFinish=res=>{
return {msg:'这是我自定义的数据'}; //返回新的响应数据
}
//异步写法
req.defaultReq.beforeFinish=async res=>{
await timeout(); //3秒后执行
return {msg:'这是我自定义的数据'}; //返回新的响应数据
}
11.设置全局错误拦截
全局 defaultReq 设置完成后针对全局有效,ajax 方法默认在你没传值的情况下优先采用的全局参数。可以通过向 ajax 方法传递参数覆盖全局的详细