zdtap-uniapp-main/api/request.js

151 lines
3.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {
base_url
} from './config.js'
const timeout = 5000;
let showModal = false
// 定义错误码
const ErrorCode = {
SUCCESS: 200,
UNAUTHORIZED: 401,
FORBIDDEN: 403,
SERVER_ERROR: 500
}
// 定义公开API白名单
const publicApis = [
'/beer/list', // 啤酒列表
'/beer/detail', // 啤酒详情
'/beer/favor/status', // 收藏状态
'/beer/review/score', // 评分
'/beer/review/list', // 评价列表
'/activity/list', // 活动列表
'/activity/detail', // 活动详情
'/bar/detail', // 酒吧详情
'/bar/list', // 酒吧列表
'/common/', // 公共接口
'/bar/brewery/getBeerInfo', // 获取酒款信息
'/bar/brewery/getReviewList', // 获取酒评列表
'/bar/brewery/getReviewScoreList', // 获取酒评评分列表
'/bar/brewery/getActivities', // 获取活动列表
'/bar/brewery/getActivityInfo', // 获取活动详情
'/bar/brewery/getBreweryInfo', // 获取品牌详情
]
// 检查是否是公开API - 使用更精确的匹配
const isPublicApi = (url) => {
return publicApis.some(api => {
if (api.endsWith('/')) {
return url.startsWith(api);
}
return url === api || url.startsWith(api + '/');
});
}
// 处理错误提示
const handleErrorMessage = (code, msg, url) => {
// 如果是公开API不显示错误提示
if (isPublicApi(url)) return;
switch (code) {
case ErrorCode.UNAUTHORIZED:
if (!showModal) {
showModal = true;
// 直接触发登录事件,显示登录弹窗
uni.$emit('needLogin');
setTimeout(() => {
showModal = false;
}, 100);
}
break;
case ErrorCode.FORBIDDEN:
uni.showToast({
title: msg || '暂无权限',
icon: 'none',
duration: 2000
});
break;
case ErrorCode.SERVER_ERROR:
uni.showToast({
title: '服务器异常,请稍后重试',
icon: 'none',
duration: 2000
});
break;
default:
if (msg) {
uni.showToast({
title: msg,
icon: 'none',
duration: 2000
});
}
}
}
export default (params) => {
let url = params.url;
let method = params.method || "get";
let data = params.data || {};
let header = {}
let token = uni.getStorageSync('token')
console.log(token)
if (token) {
header['Authorization'] = 'Bearer ' + token
}
// if (method == "post") {
// header['Content-Type'] = 'multipart/form-data'
// }
return new Promise((resolve, reject) => {
uni.request({
url: base_url +'/api'+ url,
method: method,
header: header,
data: data,
dataType: 'json',
timeout,
success(response) {
const res = response
if (res.statusCode == 200) {
console.log(res.data, '接口返回值')
if (res.data.code == ErrorCode.SUCCESS) {
resolve(res.data);
} else {
// 处理401未授权错误
if (res.data.code == ErrorCode.UNAUTHORIZED) {
// 只有非公开API才清除token
if (!isPublicApi(url)) {
uni.removeStorageSync('token')
}
}
// 显示错误提示
handleErrorMessage(res.data.code, res.data.msg, url);
reject(res.data)
}
} else {
handleErrorMessage(res.statusCode, '服务器异常', url);
reject(response)
}
},
fail(err) {
if (!isPublicApi(url)) {
uni.showToast({
title: '网络异常,请检查网络连接',
icon: 'none',
duration: 2000
})
}
reject(err)
},
// complete() {
// }
});
})
}