萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 獲取 Web 應用根目錄路徑:相容多種部署環境的最佳實踐

問題背景

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 路徑

現代簡化寫法 (ES6+)

// 僅取得 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/';

各種部署場景測試

部署 URLlocation.pathnamegetContextPath()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、添加前綴。更健壯的方案:

1. 後端注入全域變數 (推薦)

<!-- 後端模板渲染 -->
<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,零運算、零誤差、支援任意代理架構。

2. 使用 標籤

<head>
  <base href="<%= request.getContextPath() %>/">
</head>
<body>
  <img src="images/logo.png">  <!-- 自動解析為 /myapp/images/logo.png -->
  <a href="api/users">用戶列表</a>  <!-- 相對連結自動加上 base -->
</body>

注意:<base> 會影響頁面所有相對連結、錨點、圖片、腳本、樣式。錨點跳轉需改用完整路徑。

3. 模組化專案:建構時注入

// 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 配置,建構時自動處理資源路徑,無需執行期計算。

copyright © 萬盛學電腦網 all rights reserved