設定 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。
配置優先順序
#請記住設定的優先順序順序
-
命令列引數(例如
--web-hostname、--web-port) web_dev_config.yaml設定- 內建預設值