uniApp 封装的网络请求

2021-04-21  本文已影响0人  花影_62b4

http.js

var requestUrl = "XXXXXXXX";

module.exports = ({

url,

method = 'GET',

data,

callback,

noPop = false,

showError = false

}) => {

let self = this;

let token = ''

if (uni.getStorageSync('token')) {

token = uni.getStorageSync('token')

}

uni.showLoading({

title: '加载中'

})

uni.request({

header: {

'content-type': 'application/json',

"Authorization": `Bearer ${token}`,

"RuntoAccessType": "App"

},

url: requestUrl + url,

method: method,

data: data,

success(res) {

//隐藏导航条加载动画

uni.hideNavigationBarLoading();

//停止下拉刷新

uni.stopPullDownRefresh();

uni.hideLoading()

if (res.statusCode == 200) { //正常情况 

//以下判断根据自己后台接口里返回的状态码自己适配

if (res.data.Code == 200) {

callback(res)

} else {

if (res.data.Code == 401) { //登录超时

uni.showToast({

title: res.data.Message ? res.data.Message : '登录超时',

icon: 'none',

duration: 2000,

success() {

uni.reLaunch({

url: '/pages/login/login'

});

}

})

} else {

if (noPop) {} else {

uni.showToast({

title: res.data.Message ? res.data.Message : '未知错误',

icon: 'none',

duration: 2000,

success() {

if (showError) {

callback(res)

}

}

})

}

}

}

}

if (res.statusCode == 401) { //token失效,重新获取

uni.reLaunch({

url: '/pages/login/login'

});

}

},

fail(res) {

uni.hideLoading();

//隐藏导航条加载动画

uni.hideNavigationBarLoading();

//停止下拉刷新

uni.stopPullDownRefresh();

console.log(url)

uni.showToast({

title: "请求失败,请检查网络连接!",

icon: 'none',

duration: 2000

})

},

})

}

main.js

import Vue from 'vue'

import App from './App'

import http from "./utils/http.js"

Vue.config.productionTip = false

Vue.prototype.http=http;

App.mpType = 'app'

const app = new Vue({

    ...App

})

app.$mount()

上一篇下一篇

猜你喜欢

热点阅读