uniapp 使用 axios 二次封装
import Vue from 'vue'
import axios from 'axios'
const baseUrl = 'http://127.0.0.1:8080' // 服务器地址
const imageUrl = baseUrl
const staticVariables = {
BASE_URL: baseUrl,
TIME_OUT: 10000,
SSL_VERIFY: false,
DURATION: 500,
MASK: true,
TOKEN_PREFIX: 'Bearer ',
FORM_DATA: 'application/x-www-form-urlencoded',
JSON: 'application/json'
}
/*
* 创建axios实例
*/
const http = axios.create({
baseURL: staticVariables.BASE_URL,
timeout: staticVariables.TIME_OUT
})
/**
* 请求工具
* @param url
* @param method
* @param ContentType
* @param data
* @param isLoading
* @returns {Promise<unknown>}
*/
const request = (url, method, ContentType, data, isLoading = true) => {
if (isLoading) {
uni.showLoading({
title: "请求中...",
mask: staticVariables.MASK
})
}
return new Promise((resolve, reject) => {
http.request({
url,
method,
data: method === 'get' ? void 0 : data,
params: method === 'get' ? data : void 0,
headers: {
'Content-Type': ContentType,
'Authorization': uni.getStorageSync('token')
},
}).then(res => {
if (res.data.code === 200) {
resolve(res.data)
} else {
uni.showToast({
title: res.data.msg,
icon: 'none'
});
if (res.data.code === 422 || res.data.code === 424) {
Vue.prototype.$store.commit('logout')
setTimeout(() => {
uni.reLaunch({
url: '/pages/login/login'
})
}, 1000)
}
reject(res.data)
}
}).catch(err => {
reject(err)
}).finally(() => {
setTimeout(() => {
uni.hideLoading()
}, 200)
})
})
}
const get = async(url, data, isLoading) => {
return await request(url, 'get', staticVariables.JSON, data, isLoading)
}
const getForm = async(url, data, isLoading) => {
return await request(url, 'get', staticVariables.FORM_DATA, data, isLoading)
}
const post = async(url, data, isLoading) => {
return await request(url, 'post', staticVariables.JSON, data, isLoading)
}
const postForm = async(url, data, isLoading) => {
return await request(url, 'post', staticVariables.FORM_DATA, qs(data), isLoading)
}
const put = async(url, data, isLoading) => {
return await request(url, 'put', staticVariables.JSON, data, isLoading)
}
const putForm = async(url, data, isLoading) => {
return await request(url, 'put', staticVariables.FORM_DATA, qs(data), isLoading)
}
const deleted = async(url, data, isLoading) => {
return await request(url, 'delete', staticVariables.JSON, data, isLoading)
}
const deletedForm = async(url, data, isLoading) => {
return await request(url, 'delete', staticVariables.FORM_DATA, qs(data), isLoading)
}
Vue.prototype.uploadFileToServe = uploadFileToServe
Vue.prototype.get = get
Vue.prototype.getForm = getForm
Vue.prototype.post = post
Vue.prototype.postForm = postForm
Vue.prototype.put = put
Vue.prototype.putForm = putForm
Vue.prototype.deleted = deleted
Vue.prototype.deletedForm = deletedForm
export default {
uploadFileToServe, get, getForm, post, postForm, put, putForm, deleted, deletedForm
}
标签:uniapp,axios,封装,url,staticVariables,Vue,isLoading,const,data
From: https://www.cnblogs.com/snail2018/p/17849624.html