跨域
更新时间:2026-09-20
概述
跨域插件用于为服务端启用 CORS(Cross-Origin Resource Sharing,跨域资源共享)的返回 HTTP 响应头,使浏览器端的跨域请求能够正常访问网关上的 API,无需业务后端自行实现 CORS 逻辑。
生效范围:实例 / 域名 / 基础 API / Model API / Agent API。
配置字段
| 配置项 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
allow_origins |
array of string | 否 | 未配置任何 Origin 时为 ["*"] |
允许的精确 Origin,格式为 scheme://host[:port]。"*" 表示允许任意非空 Origin |
allow_origin_patterns |
array of string | 否 | [] |
允许的 Origin 模式,支持子域名和端口匹配 |
allow_methods |
array of string | 否 | GET, PUT, POST, DELETE, PATCH, OPTIONS |
预检请求允许使用的 HTTP Method。配置 "*" 时回显请求 Method |
allow_headers |
array of string | 否 | DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Authorization |
预检请求允许携带的 Header。配置 "*" 时回显请求 Header |
expose_headers |
array of string | 否 | [] |
允许浏览器读取的响应 Header,例如 X-Request-Id |
allow_credentials |
bool | 否 | false |
是否允许浏览器携带 Cookie 或认证信息 |
max_age |
int | 否 | 86400 |
浏览器缓存预检结果的时间,单位为秒 |
配置示例
允许所有来源跨域访问
适用于公开只读接口,不涉及 Cookie 等凭据。
YAML
1allow_origins:
2 - "*"
3allow_methods:
4 - GET
5 - POST
6 - OPTIONS
7allow_headers:
8 - Content-Type
9 - Authorization
10max_age: 86400
允许指定域名携带凭据访问
需要携带 Cookie 时,allow_origins 不能为 *,应精确列举或使用 allow_origin_patterns。
YAML
1allow_origin_patterns:
2 - "https://*.example.com"
3allow_methods:
4 - GET
5 - POST
6 - PUT
7 - DELETE
8 - OPTIONS
9allow_headers:
10 - "*"
11expose_headers:
12 - X-Request-Id
13allow_credentials: true
14max_age: 600
允许所有来源但不携带凭据
YAML
1allow_origins:
2 - "*"
3allow_methods:
4 - "*"
5allow_headers:
6 - "*"
7expose_headers:
8 - X-Request-Id
9allow_credentials: false
10max_age: 7200
允许多个业务子域
YAML
1allow_origin_patterns:
2 - https://*.example.com
3 - "https://*.example.org:[8080,9090]"
4allow_methods:
5 - GET
6 - POST
7 - PATCH
8allow_headers:
9 - Content-Type
10 - Authorization
11allow_credentials: true
12max_age: 3600
请求测试
普通跨域请求
Bash
1curl -i \
2 -H "Origin: https://console.example.com" \
3 https://gateway.example.com/api/items
Origin 匹配时,响应会包含:
Plain Text
1access-control-allow-origin: https://console.example.com
2vary: Origin
启用凭据或暴露响应 Header 后,还会包含:
Plain Text
1access-control-allow-credentials: true
2access-control-expose-headers: X-Request-Id
预检请求
Bash
1curl -i -X OPTIONS \
2 -H "Origin: https://console.example.com" \
3 -H "Access-Control-Request-Method: POST" \
4 -H "Access-Control-Request-Headers: Content-Type, X-Trace-Id" \
5 https://gateway.example.com/api/items
匹配成功时会直接返回空响应,示例如下:
Plain Text
1HTTP/1.1 200 OK
2access-control-allow-origin: https://console.example.com
3access-control-allow-methods: GET, POST
4access-control-allow-headers: Content-Type, X-Trace-Id
5access-control-max-age: 3600
6vary: Origin
使用说明
- 插件绑定后,网关会自动处理浏览器发出的
OPTIONS预检请求并返回对应的 CORS 响应头,无需在后端额外实现。 - 需要对整个域名下的全部 API 统一开放跨域时,建议将插件绑定到域名级别,避免逐个 API 重复配置。
max_age设置过大时,调整 CORS 配置后浏览器可能仍在使用旧的预检缓存,调试阶段建议设置较小的值。
相关操作
评价此篇文章
