uni-app中vue3版本基于uni.request配置全局请求方法

数据请求在开发中是绝对不可能少的组成部分,关于数据请求的各类组件或者方法绝对也是最多的。

本篇文章介绍一个在uni-app开发中,如何封装请求方法来提升开发速度。

一、创建http.js方法

export const baseUrl = '请求url';
export function http(url, data, method = 'GET') {
return new Promise((resolve, reject) => {
uni.request({
url: baseUrl + url,
data,
header: {
'token':'',
'Accept':'json',
'Content-Type':'application/json',
},
method,
success: (res) => {
if (res.statusCode == 200) {
//if (res.data.code == 200) {
// resolve(res.data)
//}else{
// uni.removeStorageSync('token')
// uni.navigateTo({
// url:'/pages/login/index'
// })
//}
resolve(res.data)
}else {
uni.showToast({
title: "fail" + res.statusCode,
icon: 'none'
})
}
},
fail: (res) => {
uni.showToast({
title: '服务器请求异常',
icon: 'none'
})
},
complete: () => {

}
});
})
}

二、在main.js中配置全局请求方法

// #ifdef VUE3
import { createSSRApp } from 'vue'
import { http } from '@/utils/http.js'
export function createApp() {
const app = createSSRApp(App)
app.config.globalProperties.$http = http
return {
app
}
}
// #endif

三、页面中使用全局方法

export default {
data() {
return {
}
},
computed: {},
onLoad(e) {
let _this = this
_this.$http('/api/article/index',{id:'id值'},'POST').then(res => {
if(res.code === 200){
}else{
}
})
}
}

关于请求未登录统一拦截

    在步骤一http.js中,success中根据你们后端开发者配置的未登录code值来自定义处理注释掉的内容部分。

六月初字帖坊小程序 你想要的字帖模板及工具,这里都有!