Files
2026-03-05 17:04:40 +08:00

86 lines
2.2 KiB
JavaScript
Raw Permalink 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.
/**
* 早安电台 — API 请求封装
* 支持 Promise、BaseURL 配置、自动附带 Token
*/
// 接口基础地址(预留占位符,对接后端时替换)
//const API_BASE_URL = 'https://radio.sundynix.cn/api'
const API_BASE_URL = 'http://192.168.0.184:8888'
/**
* 获取本地存储的 token
*/
function getToken() {
return wx.getStorageSync('token') || ''
}
/**
* 通用请求方法
* @param {Object} options
* @param {string} options.url - 接口路径(不含 BaseURL
* @param {string} [options.method='GET'] - 请求方法
* @param {Object} [options.data] - 请求参数
* @param {Object} [options.header] - 自定义请求头
* @returns {Promise}
*/
function request(options) {
return new Promise((resolve, reject) => {
const token = getToken()
wx.request({
url: `${API_BASE_URL}${options.url}`,
method: options.method || 'GET',
data: options.data || {},
header: {
'Content-Type': 'application/json',
'Authorization': token ? `Bearer ${token}` : '',
...options.header
},
success(res) {
if (res.statusCode >= 200 && res.statusCode < 300) {
resolve(res.data)
} else if (res.statusCode === 401) {
// Token 过期或未登录,跳转到登录
wx.removeStorageSync('token')
wx.redirectTo({ url: '/pages/splash/index' })
reject(new Error('未授权,请重新登录'))
} else {
reject(new Error(res.data.message || `请求失败: ${res.statusCode}`))
}
},
fail(err) {
reject(new Error(err.errMsg || '网络请求失败'))
}
})
})
}
/**
* 快捷方法
*/
function get(url, data) {
return request({ url, method: 'GET', data })
}
function post(url, data) {
return request({ url, method: 'POST', data })
}
function put(url, data) {
return request({ url, method: 'PUT', data })
}
function del(url, data) {
return request({ url, method: 'DELETE', data })
}
module.exports = {
API_BASE_URL,
request,
get,
post,
put,
del
}