1.创建request.js文件
2.基本使用
2.1 request.js
export default{
a:1
}
2.2 调用者使用
import $http from '@/common/api/request.js'
console.log($http.a)
3.进阶使用
3.1 request.js
export default {
a:1,
common:{
baseUrl:"http://192.168.126.1:3000/api",
data:{},
head:{
'content-type':"application/json",
'content-type':"application/x-www-form-urlencoded"
},
method:"GET",
dataType:"json"
},
request(options={}){
options.url=this.common.baseUrl+options.url
options.data=options.data || this.common.data
options.head=options.head || this.common.head
options.method=options.method || this.common.method
options.dataType=options.dataType || this.common.dataType
return new Promise((res,rej)=>{
uni.request({
...options,
success:(result) => {
if(result.statusCode !=200){
return rej()
}
let data=result
res(data)
}
})
})
}
}
3.2 调用者使用
import $http from '@/common/api/request.js'
$http.request({
url:"/index_list",
}).then((res)=>{
console.log(res)
uni.showToast({
title: '请求成功',
icon: 'none',
duration: 2000
})
}).catch((res)=>{
uni.showToast({
title:'请求失败',
icon:'none'
})
})