You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

158 lines
4.3 KiB
JavaScript

/**
* 通用uni-app网络请求
* 基于 Promise 对象实现更简单的 request 使用方式,支持请求和响应拦截
*/
import config from "./config.js"
let whiteList = [
'pages/homePage/index/index',
'pages/homePage/mine/mine',
'pages/homePage/login/login',
'pages/homePage/register/register',
'pages/mine/confirmAgreement/confirmAgreement'
]
function request(options, contentType = 'normal') {
console.log(options.url);
if (options.url.indexOf("/tmsaip") == 0) {
options.url = 'http://47.104.222.4:8081/api' + options.url
} else if(options.url.indexOf("/api") == 0){
options.url = 'http://47.104.222.4:8081' + options.url
} else {
options.url = config.baseUrl + options.url
}
options.header = {
'Content-Type': contentType == 'json' ? 'application/json;charset=UTF-8' :
'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + uni.getStorageSync('userToken') || '',
}
// options.header = {
// 'Content-Type': contentType == 'json' ? 'application/json;charset=UTF-8' :
// 'application/x-www-form-urlencoded',
// 'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySWQiOjE2NzQzMTUxNDIzOTU0NDExNTMsIlRlbmFudElkIjoxNjc0MzE1MTQyMzk1NDQxMTU0LCJBY2NvdW50IjoiaG90Y2F0IiwiTmFtZSI6Iua1i-ivleazqOWGjCIsIlN1cGVyQWRtaW4iOjIsIlRlbmFudFR5cGUiOjEwLCJUZW5hbnROYW1lIjoi5rWL6K-V5rOo5YaMIiwiRGp5VXNlcklkIjpudWxsLCJUZWwiOiIiLCJQaG9uZSI6IjEzOTc3Nzc3Nzc3IiwiRW1haWwiOiIiLCJpYXQiOjE2ODgwMzI5NzEsIm5iZiI6MTY4ODAzMjk3MSwiZXhwIjoxNjg4MTE5MzcxLCJpc3MiOiJteXNoaXBwaW5nIiwiYXVkIjoibXlzaGlwcGluZyJ9.cFI_804FaiGlhgfBa5T1q9fCqhaw4aeZnf50TFUXeek',
// }
return new Promise((resolve, reject) => {
let _config = null
options.complete = (response) => {
let statusCode = response.statusCode;
// 测试环境打印:统一的响应日志记录
_reslog(response)
if (statusCode === 200) { //成功,返回服务器返回数据
resolve(response.data);
} else {
reject(response)
}
}
_config = Object.assign({}, config, options)
// 测试环境打印:统一的请求日志记录
_reqlog(_config)
uni.request(_config);
});
}
/**
* 请求接口日志记录
*/
function _reqlog(req) {
if (process.env.NODE_ENV === 'development') {
// console.log("地址:" + req.url)
// console.log("请求参数:" + JSON.stringify(req.data))
}
//TODO 调接口异步写入日志数据库
}
/**
* 响应接口日志记录
*/
function _reslog(res) {
if (process.env.NODE_ENV === 'development') {
// console.log("响应结果:" + JSON.stringify(res.data))
}
if (res.statusCode == 401) {
getApp().globalData.isLogin = false;
let currentPage = getCurrentPage();
if (!whiteList.includes(currentPage)) {
uni.showToast({
title: '即将跳转登录',
duration: 2000,
success: () => {
uni.navigateTo({
url: '/pages/homePage/login/login?back=1',
})
}
});
}
}
}
function getCurrentPage() {
let currentRoutes = getCurrentPages(); // 获取当前打开过的页面路由数组
let currentRoute = currentRoutes[currentRoutes.length - 1].route //获取当前页面路由
let currentParam = currentRoutes[currentRoutes.length - 1].options; //获取路由参数
// 拼接参数
let param = ''
for (let key in currentParam) {
param += '?' + key + '=' + currentParam[key]
}
let localRoute = currentRoute + param;
console.log(localRoute, "当前页面路由")
return localRoute;
}
export default {
get(url, data = null, contentType = 'normal') {
let options = {
url,
data,
method: 'GET'
}
return request(options, contentType)
},
post(url, data = null, contentType = 'normal', query = 'normal') {
let options = {};
if (query == 'url') {
let str = objectToQueryString(data);
let _url = url + '?' + str;
options = {
url: _url,
method: 'POST'
}
} else {
options = {
url,
data,
method: 'POST'
}
}
return request(options, contentType)
},
put(url, data = null, contentType = 'normal') {
let options = {
url,
data,
method: 'PUT'
}
return request(options, contentType)
},
delete(url, data = null, contentType = 'normal') {
let options = {
url,
data,
method: 'DELETE'
}
return request(options, contentType)
}
}
function objectToQueryString(data) {
return Object.keys(data).map(function(key) {
return "".concat(encodeURIComponent(key), "=").concat(encodeURIComponent(data[key]));
}).join('&');
}