跳到主內容

設定 Web 開發配置檔案

集中管理 Web 開發設定,包括開發代理

Flutter Web 包含一個開發伺服器,預設情況下使用 HTTP 在隨機分配的埠上以 localhost 域提供您的應用程式。雖然命令列引數提供了修改伺服器行為的快捷方式,但本文重點介紹一種更結構化的方法:透過集中的 web_dev_config.yaml 檔案定義伺服器行為。此配置檔案允許您自定義伺服器設定(主機、埠、HTTPS 設定和代理規則),從而確保開發環境的一致性。

建立配置檔案

#

在 Flutter 專案的根目錄中新增一個 web_dev_config.yaml 檔案。如果您尚未設定 Flutter 專案,請訪問 使用 Flutter 構建 Web 應用程式 以開始。

新增配置項

#

基礎伺服器配置

#

您可以為開發伺服器定義主機、埠和 HTTPS 設定。

web_dev_config.yaml
yaml
server:
  host: "0.0.0.0" # Defines the binding address <string>
  port: 8080 # Specifies the port <int> for the development server
  https:
    cert-path: "/path/to/cert.pem" # Path <string> to your TLS certificate
    cert-key-path: "/path/to/key.pem" # Path <string> to TLS certificate key

自定義標頭

#

您還可以將自定義 HTTP 標頭注入開發伺服器的響應中。

web_dev_config.yaml
yaml
server:
  headers:
    - name: "X-Custom-Header" # Name <string> of the HTTP header
      value: "MyValue" # Value <string> of the HTTP header
    - name: "Cache-Control"
      value: "no-cache, no-store, must-revalidate"

代理配置

#

請求會按照 web_dev_config.yaml 檔案中的順序進行匹配。

基礎字串代理

#

使用 prefix 欄位進行簡單的路徑字首匹配。

web_dev_config.yaml
yaml
server:
  proxy:
    - target: "https://:5000/" # Base URL <string> of your backend
      prefix: "/users/" # Path <string>
    - target: "https://:3000/"
      prefix: "/data/"
      replace: "/report/" # Replacement <string> of path in redirected URL (optional)
    - target: "https://:4000/"
      prefix: "/products/"
      replace: ""

說明

  • /users/names 的請求將被轉發到 https://:5000/users/names
  • /data/2023/ 的請求將被轉發到 https://:3000/report/2023,因為 replace: “/report/” 替換了 /data/ 字首。
  • /products/item/123 的請求將被轉發到 https://:4000/item/123,因為 replace: "" 透過將其替換為空字串從而移除了 /products/ 字首。

高階正則表示式代理

#

您還可以使用 regex 欄位進行更靈活、更復雜的匹配。

web_dev_config.yaml
yaml
server:
  proxy:
    - target: "https://:5000/"
      regex: "/users/(\d+)/$" # Path <string> matches requests like /users/123/
    - target: "https://:4000/"
      regex: "^/api/(v\d+)/(.*)" # Matches requests like /api/v1/users
      replace: "/$2?apiVersion=$1" # Allows capture groups (optional)

說明

  • /users/123/ 的請求完全匹配第一條規則,因此它被轉發到 https://:5000/users/123/
  • /api/v1/users/profile/ 的請求以第二條規則的路徑開頭,因此它被轉發到 https://:4000/users/profile/?apiVersion=v1

配置優先順序

#

請記住設定的優先順序順序

  1. 命令列引數(例如 --web-hostname--web-port
  2. web_dev_config.yaml 設定
  3. 內建預設值