You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
import { useUserStore } from "../stores/modules/userInfo/"
// 移除本地 mock 前缀,默认不拼接任何 baseURL。
// 如需指定真实后端,请将此值改为对应域名,例如:
const baseURL = "https://hwjb.homilychart.com"
const httpInterceptor = { // 拦截前触发
invoke(options) { // 打印当前 baseURL 便于定位来源
console.log('HTTP(baseURL)=', baseURL) // 若出现旧代码将 url 设为 http://localhost:8888,强制改为真实域名
if (options.url.startsWith('http://localhost:8888')) { options.url = baseURL.replace(/\/$/, '') + options.url.replace('http://localhost:8888', '') } else if (options.url.startsWith('https://localhost:8888')) { options.url = baseURL.replace(/\/$/, '') + options.url.replace('https://localhost:8888', '') } // 仅当明确配置了 baseURL 时才拼接前缀(去掉 baseURL 尾部的斜杠,避免双斜杠)
if (baseURL && !options.url.startsWith('http')) { options.url = baseURL.replace(/\/$/, '') + options.url } // 打印最终请求地址
console.log('HTTP(finalUrl)=', options.url) // 2.请求超时,默认60s
options.timeout = 60000 console.log(options) //3 添加小程序端请求头
const sys = uni.getSystemInfoSync(); // 为对齐后端文档示例,client 固定为 ios(如需按平台设置再改回)
const client = 'ios'; options.header = { ...options.header, 'source-client': 'miniapp', // 标准头与文档头同时设置,确保兼容
'content-type': 'application/json', 'version': '1', 'client': client } //4 添加token
const memberStore = useUserStore() // const token = memberStore.userInfo?.token
const token = '6d818cda701590750245ce69393f2c32' if (token) { // 根据接口文档,token应该作为独立的header字段
options.header.Authorization = { 'token': token } } return options }}// 添加拦截器
uni.addInterceptor('request', httpInterceptor)uni.addInterceptor('uploadFile', httpInterceptor)// 添加请求函数
export const http = (options) => { return new Promise((resolve, reject) => { uni.request({ ...options, // 1.请求成功
success: (result) => { if (result.statusCode >= 200 && result.statusCode < 300) { resolve(result.data) } else if (result.statusCode === 401) { // 清除登录信息
const memberStore = useUserStore() memberStore.clearUserInfo() // 提示用户重新登录
uni.navigateTo({ url: '/pages/login/login' }) reject(result) } else { uni.showToast({ title: (result.data).msg || '请求失败', icon: 'none' }) reject(result) } }, // 2.请求失败
fail: (err) => { reject(err) uni.showToast({ title: '网络错误', icon: 'none' }) } }) })}
|