feat: MC Report System - MySQL + Express + Vanilla JS SPA
This commit is contained in:
45
public/js/api.js
Normal file
45
public/js/api.js
Normal file
@@ -0,0 +1,45 @@
|
||||
const API = {
|
||||
base: '/api',
|
||||
_key: window.__API_KEY__ || '',
|
||||
|
||||
async req(method, path, data) {
|
||||
const token = Auth.token();
|
||||
const headers = {};
|
||||
if (token) headers['Authorization'] = `Bearer ${token}`;
|
||||
if (this._key) headers['x-api-key'] = this._key;
|
||||
const opts = { method, headers };
|
||||
if (data instanceof FormData) opts.body = data;
|
||||
else if (data && method !== 'GET') { headers['Content-Type'] = 'application/json'; opts.body = JSON.stringify(data); }
|
||||
opts.headers = headers;
|
||||
const res = await fetch(this.base + path, opts);
|
||||
const ct = res.headers.get('content-type');
|
||||
if (ct && ct.includes('application/json')) {
|
||||
const json = await res.json();
|
||||
if (!res.ok) throw new Error(json.error || '请求失败');
|
||||
return json;
|
||||
}
|
||||
if (!res.ok) throw new Error('请求失败');
|
||||
return res;
|
||||
},
|
||||
|
||||
get(p) { return this.req('GET', p); },
|
||||
post(p, d) { return this.req('POST', p, d); },
|
||||
put(p, d) { return this.req('PUT', p, d); },
|
||||
|
||||
async download(path) {
|
||||
const token = Auth.token();
|
||||
const h = {};
|
||||
if (token) h['Authorization'] = `Bearer ${token}`;
|
||||
if (this._key) h['x-api-key'] = this._key;
|
||||
const res = await fetch(this.base + path, { headers: h });
|
||||
if (!res.ok) throw new Error('下载失败');
|
||||
const blob = await res.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
const disp = res.headers.get('content-disposition');
|
||||
a.download = disp?.match(/filename=(.+)/)?.[1] || 'export.csv';
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user