uniapp request请求封装,vue axios也可用此模式封装
import store from "@/store/index.js"
var baseUrl = "http://192.168.0.1";
//baseUrl 为统一的配置的请求地址, 例如:http://192.168.0.1
//store 为vuex
// 封装请求
const request = (method, url, options) => {
let methods = '';
let headers = {};
let token = store.state.token ? store.state.token : '';//存起来的token
switch (method) {
case 'get':
methods = 'GET'
headers = {
'Content-Type': 'application/json;charset=UTF-8',
'Authorization': token
}
break;
case 'post':
methods = 'POST'
headers = {
'Content-Type': 'application/json;charset=UTF-8',
'Authorization': token
}
break;
case 'postForm':
methods = 'POST'
headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'Authorization': token
}
break;
default:
break;
}
let hideLoading = false,
loadingText = 'loading...';
if (options) { //如果有options
if (options.hideLoading) {
hideLoading = options.hideLoading
delete options.hideLoading
}
if (options.loadingText) {
loadingText = options.loadingText
delete options.loadingText
}
}
//用Promise 返回后端返回的数据
return new Promise((resolve, reject) => {
if(!hideLoading){
uni.showLoading({
title: loadingText
})
}
let urls = '';
if (url.indexOf('http') == 0 || url.indexOf('https') == 0) {
urls = `${url}`
} else {
urls = `${baseUrl}${url}`
}
uni.request({
url: urls,
method: methods,
data: options,
header: headers,
success: res => {
if (res.statusCode == 200) {
if(res.data.recode == '200'){
resolve(res.data);
}else{
uni.showToast({
title: res.data.msg,
icon: 'none'
})
}
} else {
uni.showToast({
title: '请求错误(' + res.statusCode + ')',
icon: 'none'
})
reject({
'msg': '请求错误(' + res.statusCode + ')'
})
}
},
fail: e => {
// checkError(e, reject);
uni.showToast({
title: '接口请求超时',
icon: 'none'
})
},
complete: () => {
uni.hideLoading();
}
})
}
export default {
get: (methods, url, options) => {
return request('get', url, options)
}
// JOSN格式
post: (url, options) => {
return request('post', url, JSON.stringify(options))
},
// form-data格式
postForm: (url, options) => {
return request('postForm', url, options)
},
}
然后main.js全局注册
Vue.$api = Vue.prototype.$api = api;
页面中使用
let urls = "user/checkUserPhone";//请求地址
let params = {id:1} //参数
this.$api.post(urls,params).then(res => {
console.log("检查手机号是否存在", res)
})
以上方法如有问题欢迎指出,一起探讨,也可根据这个修改自己想要的方式