SmartAssiter-Discard/api/httpInstance.uts
2026-09-02 16:10:57 +08:00

90 lines
2.5 KiB
Plaintext
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 { getToken } from "../common/auth"
import { clearAllData } from "../common/auth"
// 可选后台服务器列表
export type ServerItem = {
name: string
url: string
}
export const SERVER_LIST: ServerItem[] = [
{ name: "正式 ssl (evmtapp.clenergy.com)", url: "https://evmtapp.clenergy.com:20096" } as ServerItem,
{ name: "测试 (47.107.245.120)", url: "http://47.107.245.120:30081" } as ServerItem,
{ name: "DEBUG (192.168.13.158)", url: "http://192.168.13.158:30081" } as ServerItem
]
let recordBaseUrl: string | null = null
// 读取当前后台服务器地址(内存 + 本地),未选择过则默认第一个
export function getBaseUrl(): string {
if (recordBaseUrl != null && (recordBaseUrl as string).length > 0) {
return recordBaseUrl as string
}
const t = uni.getStorageSync('serverBaseUrl') as string | null
if (t != null && t.length > 0) {
recordBaseUrl = t
return t
}
return SERVER_LIST[0].url
}
// 保存后台服务器地址(内存 + 本地),下次启动直接加载
export function setBaseUrl(url: string) {
recordBaseUrl = url
uni.setStorageSync('serverBaseUrl', url)
}
export type HttpMethod = "GET" | "POST" | "PUT" | "DELETE"
// 请求参数类型
export type HttpRequest = {
url: string
method?: HttpMethod
data?: any
header?: UTSJSONObject // 这里用 UTSJSONObject
}
// 封装请求
export function $http(params: HttpRequest): Promise<UTSJSONObject> {
return new Promise((resolve, reject) => {
// 1. 准备 header
let baseHeader: UTSJSONObject = params.header ?? {} as UTSJSONObject
baseHeader["Content-Type"] = "application/json"
// 2. 读 token,有就加 Authorization
const token = getToken()
if (token != null && token.length > 0) {
baseHeader["Authorization"] = token
}
// console.log("url = ", getBaseUrl() + params.url)
// console.log("method = ", params.method)
// console.log("data = ", params.data)
// console.log("header = ", baseHeader)
// 3. 发请求
uni.request({
url: getBaseUrl() + params.url,
method: params.method ?? "GET",
data: params.data ?? {} as UTSJSONObject,
header: baseHeader,
success: (res) => {
if(res.statusCode == 401) {
clearAllData()
uni.reLaunch({
url: '/pages/login/login'
})
}
const result: UTSJSONObject = {
statusCode: res.statusCode,
data: res.data
} as UTSJSONObject
resolve(result)
},
fail: (err) => {
reject(err)
}
})
})
}