设置 Web 开发配置文件
集中 Web 开发设置,包括开发代理
Flutter Web 包含一个开发服务器,默认情况下使用 HTTP 在随机分配的端口上的 localhost 域名提供您的应用程序。虽然命令行参数提供了一种快速修改服务器行为的方式,但本文档重点介绍一种更结构化的方法:通过集中的 web_dev_config.yaml 文件定义服务器行为。此配置文件允许您自定义服务器设置——主机、端口、HTTPS 设置和代理规则——确保一致的开发环境。
创建配置文件
#将 web_dev_config.yaml 文件添加到 Flutter 项目的根目录。如果您尚未设置 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设置- 内置默认值