better-staridc-MNBT
1import axios from 'axios'
2import { MessagePlugin } from 'tdesign-vue-next'
3
4/**
5 * MNBT 主页/售卖 SPA 路由 API 封装
6 *
7 * 插件(user_info / balance / hosting_shop)通过 P2 通用路由暴露 JSON API:
8 * POST/GET {routeBase}/account/api/login 等
9 * routeBase 由 PHP 入口注入(index.php?_r=),响应为 { code, ...extra } 结构:
10 * - code === 'ok' → 成功,extra 为数据载荷
11 * - code === 'not_login' → 未登录(前端跳登录页)
12 * - 其他 code → 失败消息
13 */
14
15function getBoot() {
16 return window.__TD_BOOT__ || {}
17}
18
19/** 读取 CSRF token(meta 优先,回退 cookie) */
20export function getCsrfToken() {
21 const meta = document.querySelector('meta[name="csrf-token"]')
22 if (meta && meta.content) return meta.content
23 try {
24 const cookies = document.cookie.split('; ')
25 for (const c of cookies) {
26 const idx = c.indexOf('=')
27 if (idx > -1 && c.slice(0, idx) === 'MNBT_CSRF_TOKEN') {
28 return decodeURIComponent(c.slice(idx + 1))
29 }
30 }
31 } catch { /* ignore */ }
32 return ''
33}
34
35const http = axios.create({ timeout: 60000 })
36
37/** 构造完整 API URL */
38export function apiUrl(path) {
39 const boot = getBoot()
40 const base = boot.routeBase || '/index.php?_r='
41 return base + path.replace(/^\//, '')
42}
43
44/**
45 * 发送路由 API 请求
46 * @param {string} method GET|POST
47 * @param {string} path 路由路径(/account/api/me)
48 * @param {object} data POST 表单数据
49 * @param {{silent?:boolean}} opts
50 * @returns {Promise<{ok:boolean, code:string, message:string, data:object, raw:object}>}
51 */
52export async function routeRequest(method, path, data = {}, { silent = false } = {}) {
53 try {
54 let res
55 if (method === 'GET') {
56 res = await http.get(apiUrl(path), { params: data })
57 } else {
58 const body = new URLSearchParams()
59 Object.keys(data || {}).forEach((k) => {
60 const v = data[k]
61 if (v === undefined || v === null) return
62 body.append(k, String(v))
63 })
64 const token = getCsrfToken()
65 if (token && !body.get('_csrf')) body.append('_csrf', token)
66 res = await http.post(apiUrl(path), body, {
67 headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
68 })
69 }
70 const raw = res.data
71 if (raw && typeof raw === 'object' && typeof raw.code === 'string') {
72 if (raw.code === 'ok') {
73 return { ok: true, code: 'ok', message: 'ok', data: raw, raw }
74 }
75 if (raw.code === 'not_login') {
76 return { ok: false, code: 'not_login', message: '请先登录', data: raw, raw }
77 }
78 return { ok: false, code: raw.code, message: raw.code || '请求失败', data: raw, raw }
79 }
80 // 兼容 { success:true, ... } 风格
81 if (raw && typeof raw === 'object' && raw.success === true) {
82 return { ok: true, code: 'ok', message: raw.msg || 'ok', data: raw, raw }
83 }
84 if (raw && typeof raw === 'object' && raw.success === false) {
85 const msg = raw.msg || raw.code || raw.message || '请求失败'
86 return { ok: false, code: msg, message: msg, data: raw, raw }
87 }
88 return { ok: true, code: 'ok', message: 'ok', data: raw ?? {}, raw }
89 } catch (e) {
90 let msg = e.message || '网络错误'
91 const body = e?.response?.data
92 if (typeof body === 'string' && body.trim()) {
93 const plain = body.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim()
94 if (plain) msg = plain.slice(0, 160)
95 } else if (body && typeof body === 'object') {
96 msg = body.code || body.msg || body.message || msg
97 }
98 console.error(`[homeApi] ${method} ${path} 异常:`, e, body)
99 if (!silent) MessagePlugin.error(msg)
100 return { ok: false, code: msg, message: msg, data: null, raw: body ?? null }
101 }
102}
103
104/** GET 快捷方法 */
105export async function apiGet(path, params = {}, opts = {}) {
106 return routeRequest('GET', path, params, opts)
107}
108
109/** POST 快捷方法 */
110export async function apiPost(path, data = {}, opts = {}) {
111 return routeRequest('POST', path, data, opts)
112}
113
114/** 未登录统一处理:返回 true 表示已拦截跳转 */
115export function handleNotLogin(result) {
116 if (!result.ok && result.code === 'not_login') {
117 window.location.hash = '#/login'
118 return true
119 }
120 return false
121}
122
123export default http