抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

摘要:无。

环境

Windows 10 企业版 LTSC 21H2
Java 1.8
Maven 3.6.3
Spring 5.3.31
Spring Boot 2.7.18
Spring Cloud 2021.0.5
Spring Cloud Gateway 3.1.4

1 跨域策略

通过配置文件声明跨域策略:

application.yml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
spring:
cloud:
gateway:
globalcors:
# 放行预检请求
add-to-simple-url-handler-mapping: true
# 配置跨域策略
cors-configurations:
# 所有路径生效
'[/**]':
# 允许携带等凭证信息
allow-credentials: true
# 允许访问的来源地址
allowed-origins:
- https://www.a.com
- https://www.b.com
# 允许访问的请求方法
allowed-methods:
- GET
- POST
- PUT
- DELETE
- OPTIONS
# 允许访问的请求头
allowed-headers: "*"

2 响应头去重

如果网关和下游服务都配置了跨域,响应中会出现重复的响应头,导致浏览器报错,此时应遵循跨域只在网关层配置一次的原则,关闭下游服务的跨域配置。

如果下游无法关闭,就需要在网关上对跨域响应头去重:

application.yml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
spring:
cloud:
gateway:
routes:
- id: cors-route
uri: http://127.0.0.1:8080
predicates:
- Path=/demo/**
filters:
- name: DedupeResponseHeader
args:
# 指定响应头名称
name:
- Access-Control-Allow-Origin
- Access-Control-Allow-Credentials
# 指定去重策略,RETAIN_FIRST表示只保留第一个值
strategy: RETAIN_FIRST

评论