1.新建request文件夹,并新建config.js index.js http.js
2.http.js代码
import {baseURL,baseURL1} from './config.js';
let BASEURL = baseURL // 调整当前环境
let BASEURL2 = baseURL1 // 调整当前环境
let contentType = {
urlencoded:'application/x-www-form-urlencoded;charset:utf-8;',
json:'application/json',
}
/*
* 全局请求封装
* @param path 请求路径
* @param method 请求类型(GET/POST/DELETE等)
* @oaram data 请求体数据
* @oaram hasToken 是否带token
* @oaram type content-type
* @param loading 请求未完成是是否显示加载中,默认为true
*/
export default (path, method, data = {},hasToken = true,type = 'urlencoded', loading = true,) => {
let token = undefined
if(hasToken){
// 获取存储token
token = uni.getStorageSync("TOKEN");
}
if (loading) {
uni.showLoading({
title: "加载中",
mask: true
});
};
//根据token进行调用函数
if (hasToken) {
return tokenRequest(path, method, data,token,type, loading)
} else {
return noTokenRequest(path, method, data,type, loading)
}
};
// 无token时发送请求函数
function noTokenRequest(path, method, data,type, loading) {
return new Promise((resolve, reject) => {
uni.request({
url: BASEURL2 + path,
method: method,
data,
header:{
'content-type': contentType[type]
},
success(response) {
// console.log('%c响应拦截:', ' background:green', response);
/* if (response.data.code === 3001) {
// logout()
} */
/* if (response.data.code !== 20) {
uni.showToast({
icon: "none",
duration: 4000,
title: response.data.msg
});
} */
console.log(response.data)
resolve(response.data);
},
fail(err) {
uni.showToast({
icon: "none",
title: '服务响应失败'
});
console.error(err);
reject(err);
},
complete() {
uni.hideLoading();
}
});
});
}
// 有token时发送请求函数
function tokenRequest(path, method, data,token, type, loading ) {
return new Promise((resolve, reject) => {
urlRequest(path, method, data, token, type, loading)
});
}
function urlRequest(path, method, data, token, type, loading) {
uni.request({
url: BASEURL + path,
method: method,
data,
header: {
'content-type': contentType[type],
"Authorization": token
},
success(response) {
// console.log('%c响应拦截:', ' background:green', response);
if (response.data.code === 40101) {
// logout()
}
// console.log(response.data)
resolve(response.data);
},
fail(err) {
uni.showToast({
icon: "none",
title: '服务响应失败'
});
console.error(err);
reject(err);
},
complete() {
uni.hideLoading();
}
});
}
3.添加自动刷新接口
在
function tokenRequest(path, method, data, token, type, loading) {
return new Promise((resolve, reject) => {
const now = new Date().getTime();
const expiresTime = uni.getStorageSync("tokenTime"); //token时间
const expired = parseInt(expiresTime) - now <= 0;
if (expired) {
//token自动续期
uni.request({
url: BASEURL + "/login/automaticRenewalAccount",
method: "post",
data: {
token: token
},
header: {
'content-type': "application/x-www-form-urlencoded;charset:utf-8"
},
success(response) {
uni.setStorageSync('token', response.data.data.token);//token
uni.setStorageSync('tokenTime', response.data.data.expirationTime);//token时间
urlRequest(path, method, data, response.data.data.token, type, loading)
},
fail(err) {
uni.showToast({
icon: "none",
title: '服务响应失败'
});
reject(err);
},
complete() {
uni.hideLoading();
}
})
} else {
urlRequest(path, method, data, token, type, loading)
}
});
}
- config.js
export const baseURL = "http://xxxx"; //本地后台端口
export const baseURL1 = "http://xxxx"; //不需要token的接口
5.index.js
import request from "./http.js"
export function get (url, data, hasToken,type) {
//return request(url, 'GET', data, hasToken, type, false)
return request(url, 'GET', data, hasToken, 'urlencoded', false)
}
export function post(url, data,hasToken,type) {
return request(url, 'POST', data, hasToken, type, false)
//return request(url, 'POST', data, hasToken, 'json', false)
}
6.新建api文件夹
新建js文件,比如login.js,代码:
import { get,post } from "@/request/index.js";
//需要token的接口
export const login =(data)=> post('/login', data)
//不需要token接口为false,否则为true
export const login = (data) => {
return post("/xxx", data, false);
};
//json格式接口
export const login = (data) => {
return post("/xxx", data, true,‘json’);
};
7.在页面中使用
import { login } from "/api/login.js";
login({id:1}).then(async res => {})
完结
根据需求修改代码。