1.新建request.js
if (process.env.NODE_ENV === 'development') {
baseUrl = 'http://localhost:8000'
} else {
baseUrl = 'https://*******.**'
console.log = () => {}
}
const sendRequest = (url, method = 'GET', data = {}, contentType) => {
let types = '';
if (method == 'POST' && !contentType) {
types = 'application/x-www-form-urlencoded'
} else if (method == 'POST' && contentType) {
types = contentType
} else {
types = 'application/json';
}
var bases = baseUrl + url;
var token = uni.getStorageSync('token') || '';
return new Promise(function(resolve, reject) {
uni.showLoading({
title: '加载中...'
});
uni.request({
url: bases,
data: data,
method: method,
header: {
'Content-Type': 'application/json',
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Authorization':'Bearer '+ uni.getStorageSync("token"),
},
success(res) {
uni.hideLoading();
var code = res.data.code;
console.log("res",res)
switch (code) {
case 20001:
uni.showModal({
title: '登录提示',
content: '无权访问!请重新登录后再来操作',
showCancel:false,
success:ress => {
uni.reLaunch({
url:'/pages'
})
}
})
break;
case 20002:
uni.showModal({
title: '登录提示',
content: '身份已过期,请重新登录后再来操作!',
showCancel:false,
success:ress => {
uni.redirectTo({
url:'/pages'
})
}
})
break;
case 20003:
uni.showModal({
title: '登录提示',
content: 'Token生成失败,请重新登录!',
showCancel:false,
success:ress => {
uni.redirectTo({
url:'/pages'
})
}
})
break;
case 20005:
uni.showModal({
title: '登录提示',
content: '访问被禁止,请重新登录!',
showCancel:false,
success:ress => {
uni.redirectTo({
url:'/pages'
})
}
})
break;
case 500:
uni.showModal({
title: '登录提示',
content: '系统错误,请重新登录!',
success:ress => {
if (ress.confirm) {
uni.redirectTo({
url:'/pages'
})
}
}
})
break;
default:
resolve(res);
break;
}
},
fail(err) {
uni.hideLoading();
uni.showToast({title:"出错啦,请稍后再试",icon:"error"});
reject(err);
}
})
})
}
module.exports.sendRequest = sendRequest
main.js
import http from './common/vmeitime-http/request.js'
Vue.config.productionTip = false
Vue.prototype.$http = http
GET
this.$http.sendRequest(`/api/details/${id}`, 'GET', {}).then(res => {
if(res.data) {
console.log('val——',res.data)
} else {
uni.showToast({title:'数据不存在',icon:"error"});
}
}).catch(err => {
})
POST
this.$http.sendRequest('/api/login', 'POST', {}).then(res => {
}).catch(err => {
})