Web 應用部署時可能位於:
https://example.com/https://example.com/myapp/https://example.com/path/to/app/前端 JS 需動態構建 API 路徑、資源路徑,硬編碼會導致部署遷移失敗。需一個通用函式取得應用根路徑 (Context Path)。
/**
* 獲取 Web 應用根路徑 (Context Path)
* 範例:
* https://example.com/ → "/"
* https://example.com/myapp/ → "/myapp/"
* https://example.com/myapp/page.html → "/myapp/"
* https://example.com/myapp/dir/page.html → "/myapp/"
*/
function getRootPath() {
// 完整 URL:https://example.com/myapp/dir/page.html?query=1
var fullPath = window.location.href;
// 路徑部分:/myapp/dir/page.html
var pathName = window.location.pathname;
// 找到 pathName 在 fullPath 中的位置
var pos = fullPath.indexOf(pathName);
// 協定+域名+埠口:https://example.com
var hostPath = fullPath.substring(0, pos);
// 取得 context path:/myapp/
// pathname 以 / 開頭,找第二個 / 的位置
var contextPath = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
return hostPath + contextPath; // 含協定域名:https://example.com/myapp
}
// 使用
var webRoot = getRootPath(); // "https://example.com/myapp"
var apiUrl = webRoot + '/api/users'; // 完整 API 路徑
// 僅取得 context path (不含域名):/myapp/
function getContextPath() {
var path = location.pathname;
return path.substring(0, path.indexOf('/', 1) + 1) || '/';
}
// 取得完整基礎 URL:https://example.com/myapp/
function getBaseUrl() {
return location.origin + getContextPath();
}
// 使用
const API_BASE = getBaseUrl() + '/api/';
| 部署 URL | location.pathname | getContextPath() | getBaseUrl() |
|---|---|---|---|
| https://a.com/ | / | / | https://a.com/ |
| https://a.com/app/ | /app/ | /app/ | https://a.com/app/ |
| https://a.com/app/page | /app/page | /app/ | https://a.com/app/ |
| https://a.com/app/dir/page | /app/dir/page | /app/ | https://a.com/app/ |
| https://a.com:8080/app/ | /app/ | /app/ | https://a.com:8080/app/ |
某些反向代理、容器環境會修改 Host、添加前綴。更健壯的方案:
<!-- 後端模板渲染 -->
<script>
window.APP_CONFIG = {
contextPath: '<%= request.getContextPath() %>', // JSP
// contextPath: '@Context.Request.PathBase', // ASP.NET Core
// contextPath: '{{ request.SCRIPT_NAME }}', // Jinja2
apiBase: '<%= request.getContextPath() %>/api/',
version: '1.2.3'
};
</script>
前端直接使用 window.APP_CONFIG.apiBase,零運算、零誤差、支援任意代理架構。
<head>
<base href="<%= request.getContextPath() %>/">
</head>
<body>
<img src="images/logo.png"> <!-- 自動解析為 /myapp/images/logo.png -->
<a href="api/users">用戶列表</a> <!-- 相對連結自動加上 base -->
</body>
注意:<base> 會影響頁面所有相對連結、錨點、圖片、腳本、樣式。錨點跳轉需改用完整路徑。
// vite.config.js / webpack.config.js
define: {
'process.env.BASE_URL': JSON.stringify('/myapp/')
}
// 前端代碼
const API_BASE = process.env.BASE_URL + 'api/';
| 錯誤代碼 | 問題 | 修正 |
|---|---|---|
| pathname.substr(1).indexOf('/') | 根目錄時 indexOf 回傳 -1,+1 變 0,substring(0,0) 回傳空字串 | 加上 || '/' 兜底 |
| 硬編碼 '/myapp/' | 部署路徑變更即失效 | 動態計算或後端注入 |
| 用 location.host + '/myapp' | 忽略了協定、埠口、子目錄 | 用 location.origin |
| 單頁應用 (SPA) 歷史模式 | 刷新子路由 404 | 伺服器配置 fallback 到 index.html |
獲取應用根路徑看似簡單,實則涉及部署架構、反向代理、容器網路等複雜因素。最佳實踐:後端模板注入全域設定物件,前端零運算直接使用。若無後端模板 (純靜態站點),使用 location.origin + contextPath 動態計算並加上兜底邏輯。現代建構工具 (Vite, Webpack, Next.js) 皆內建 base / publicPath 配置,建構時自動處理資源路徑,無需執行期計算。