項目中多個 JS 文件發起 AJAX 請求,基礎 URL 相同(如 /api/v1),需統一管理、便於維護。
| 方案 | 優點 | 缺點 |
|---|---|---|
全局變量 window.API_BASE | 簡單直接 | 污染全局、無模塊化、易衝突 |
config.js 輸出常量,<script> 引入 | 無構建工具也可用 | 需保證加載順序、非模塊化 |
ES Module export const BASE = ... | 標準模塊化、樹搖優化 | 需構建/瀏覽器支持 |
封裝 Request 類/函數 | 統一攔截、錯誤處理、攜帶 Token | 稍多代碼 |
// utils/request.js
const BASE_URL = 'https://api.example.com/v1';
export async function request(url, options = {}) {
const res = await fetch(BASE_URL + url, {
headers: { 'Content-Type': 'application/json', ...options.headers },
...options
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
// 業務文件
import { request } from './utils/request';
const users = await request('/users');
const user = await request('/users/1', { method: 'POST', body: JSON.stringify(data) });
// config.js
window.APP_CONFIG = { API_BASE: '/api/v1' };
// 其它 JS 確保在 config.js 之後加載
$.ajax({ url: APP_CONFIG.API_BASE + '/users', ... });