Browse Source

添加请求方法

master
邓宏 2 years ago
parent
commit
b51e4b5cc5
  1. 47
      common/request.js
  2. 1
      pages/index/index.vue
  3. 4
      store/index.js

47
common/request.js

@ -0,0 +1,47 @@
import store from "@/store"
function host(host='default'){
return({
default:"http://127.0.0.1:8080"
})[host]
}
//加载状态
let loadNum=0
// 自定义封装uniapp请求
const request=async function(url,param={}){
loadNum++;
uni.showLoading({
title:"加载中",
mask:true,
})
//路径数据
var pathData=Object.entries({...(url.match(/\?(.+)/)||{1:""})[1].split("&").map(v=>v.split('=')).filter(v=>v[0]&&v[1]).reduce((a,b)=>{a[b[0]]=b[1];return a},{}), ...(param.pathData||{})}).map(v=>`${v[0]}=${v[1]}`).join("&")
var res=await uni.request({
url:(param.host||host())+('/'+url).replace(/\/{2}/,'/').replace(/\?.+/,"")+`?${pathData}`,
method:param.method||"get",
data:param.data,
header:Object.assign(param.header||{}, {"token":uni.getStorageSync('token')})
})
setTimeout(()=>{
loadNum--;
if(loadNum<=0){
uni.hideLoading()
}
},600)
if(res[1]){
if(res[1].data.code==401){
return{statu:false, msg:"登录超时!"}
}
else if(res[1].data.code==0)return { statu:true, data:res[1].data }
else if(res[1].statusCode==404)return {statu:false,msg:"地址不存在!"}
else return {statu:false,msg:res[1]?.data?.msg||"服务器错误!", code:res[1]?.data?.code??res[1].statusCode}
}else{
return { statu:false, msg:"服务器错误!"}
}
}
export default request

1
pages/index/index.vue

@ -34,6 +34,7 @@
</template> </template>
<script> <script>
import request from '@/common/request.js'
export default { export default {
data() { data() {
return { return {

4
store/index.js

@ -5,6 +5,8 @@ Vue.use(Vuex)
export default new Vuex.Store({ export default new Vuex.Store({
state:{}, state:{},
getters:{}, getters:{},
mutations:{}, mutations:{
},
actions:{} actions:{}
}) })
Loading…
Cancel
Save