zdtap-uniapp-main/api/request.js

118 lines
2.8 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
// 定义公开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.includes('/')) {
return url.includes(api);
}
// 如果是通配符匹配
return url.split('/').includes(api);
});
}
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 == 200) {
resolve(res.data);
} else if (res.data.code == 401 && !isPublicApi(url)) {
uni.clearStorageSync()
if (showModal) return
showModal = true
uni.showModal({
title: "提示",
content: res.data.msg || "身份已过期,请重新登录",
showCancel: false,
success() {
showModal = false
uni.navigateTo({
url: '/pages/index/chooseLogin'
})
},
});
} else {
// 对于公开接口的401错误不显示错误提示
if (!isPublicApi(url)) {
uni.showToast({
title: res.data.msg || '请求失败',
icon: 'none',
duration: 3000,
})
}
reject(res.data)
}
} else {
uni.showToast({
title: '服务器异常',
icon: 'none',
duration: 2000
})
reject(response)
}
},
fail(err) {
uni.showToast({
title: '网络异常',
icon: 'none',
duration: 2000
})
reject(err)
},
// complete() {
// }
});
})
}