1. - http.js 跟目录新建server文件夹
import LocalCache from "@/utils/cache.js"
import {
login
} from "@/server/api/login.js"
const ErrStatus = {
400: '请求参数错误',
401: '身份验证已过期,请重新登录',
403: '服务器拒绝请求',
404: '请求地址错误',
405: '请求方法错误',
408: '请求超时 ',
500: '服务器错误 ',
501: '服务器错误 ',
502: '服务器错误 ',
}
function http(BaseUrl, options = {}, showLoading = true) {
options.url = `${BaseUrl}${options.url}`;
console.log('请求信息-', options);
if (options.header) {
options.header = {
...options.header,
'Authorization': ''
}
} else {
options.header = {
'Authorization': ''
}
}
if (userInfo && userInfo.token) {
options.header.Authorization = `Bearer ${userInfo.token}`
}
return new Promise((resolved, rejected) => {
if (showLoading) {
uni.showLoading({
mask: true
})
}
options.success = (res) => {
console.log('返回来的信息-',res);
if (res.statusCode == 200||res.statusCode == 201) {
if(res.data&&res.data.type=='success'){
resolved(res)
}else if(res.data==''){
resolved(res)
}else{
uni.showToast({
icon: 'none',
duration: 3000,
title: `${res.data.message}`
});
rejected(res)
}
} else {
uni.showToast({
icon: 'none',
duration: 3000,
title: `${ErrStatus[res.statusCode]}`
});
if (res.statusCode === 401) {
LocalCache.clearCache()
setTimeout(()=>{
uni.reLaunch({
url: '/pages/views/login/login'
})
},1000)
}
rejected(res)
}
};
options.fail = (err) => {
uni.showToast({
icon: 'error',
duration: 2000,
title: ErrStatus[res.statusCode]
});
rejected(err);
};
options.complete = () => {
uni.hideLoading()
}
uni.request(options);
});
}
export default http;
2. -baseUrl.js server文件夹下面新建config文件夹
let BaseUrl=''
if(process.env.NODE_ENV==="development"){
console.log('环境判断:开发环境')
BaseUrl=''
}else{
console.log('环境判断:正式环境')
BaseUrl=''
}
export default BaseUrl
3.test.js 放在server文件夹下面的api文件夹
import http from "@/server/http.js"
import BaseUrl from "@/server/config/baseUrl.js"
export function postTest(data){
return http(BaseUrl,{
url:url,
method:'POST',
data:data
},false)
}
export function getTest(){
return http(BaseUrl,{
url:url,
method:'GET'
})
}
4.页面使用
import {postTest,getTest} from "@/server/api/test.js"
methods: {
submitGet:async function(){
const res = await getTest()
console.log(res)
},
submitPost:async function(){
const res = await postTest({data:'阿毛子'})
console.log(res)
}
}