【Spring Cloud】Spring Cloud Gateway 中配置跨域

Spring Cloud Gateway 中配置跨域

开发高并发系统时有三把利器用来保护系统:缓存、降级和限流。API网关作为所有请求的入口,请求量大,我们可以通过对并发访问的请求进行限速来保护系统的可用性。

在Spring Cloud Gateway 中配置跨域有两种方式,分别是代码配置方式和配置文件方式。

一、代码配置方式配置跨域

代码配置方式配置跨域,代码清单如下所示:

java 复制代码
@Configuration
public class CorsConfig {
	@Bean
	public WebFilter corsFilter() {
		return (ServerWebExchange ctx, WebFilterChain chain) -> {
			ServerHttpRequest request = ctx.getRequest();
			if(CorsUtils.isCorsRequest(request)) {
				HttpHeaders requestHeaders = request.getHeaders();
				ServerHttpResponse response = ctx.getResponse();
				HttpMethod requestMethod = requestHeaders.getAccessControlRequestMethod();
				HttpHeaders headers = response.getHeaders();
				headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, requestHeaders.getOrigin());
				headers.addAll(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders.getAccessControlRequestHeaders());
				if(requestMethod != null) {
					headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, requestMethod.name());
				}
				headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
				headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "*");
				if(request.getMethod() == HttpMethod.OPTIONS){
					response.setStatusCode(HttpStatus.OK);
					return Mono.empty();
				}
			}
			return chain.filter(ctx);
		};
	}
}

二、配置文件方式配置跨域

配置文件方式配置跨域,代码清单如下所示:

java 复制代码
spring:
	cloud:
		gateway:
			globalcors:
				corsConfigurations:
					'[/**]':
						allowedOrigins: "*"
						exposedHeaders:
						- content-type
						allowedHeaders:
						- content-type
						allowCredentials: true
						allowedMethods:
						- GET
						- OPTIONS
						- PUT
						- DELETE
						- POST

本文完结!

相关推荐
子夜四时歌31 分钟前
Python详细安装与环境搭建
开发语言·python
Jinkxs32 分钟前
SkyWalking - Python 应用追踪:基于 skywalking-python 的埋点
开发语言·python·skywalking
大头博士先生32 分钟前
【3月考】二级Python最新真题及满分代码合集(基本操作题部分)
开发语言·python
白狐_79833 分钟前
【实战架构】一人抵一家设计公司:基于 ComfyUI + Python RPA + Photoshop 的全自动化工业制图工作流
python·photoshop·rpa
shengli72233 分钟前
Python在金融科技(FinTech)中的应用
jvm·数据库·python
xcLeigh34 分钟前
IoTDB Python原生接口全攻略:从基础读写到高级实战
开发语言·数据库·python·api·iotdb·原生接口·读写数据
User_芊芊君子34 分钟前
文科生封神!Python+AI 零门槛变现:3 天造 App,指令即收入(附脉脉 AI 沙龙干货)
开发语言·人工智能·python
MeowNeko34 分钟前
为什么说程序员重命名时电脑不要带中文?记一次python manage.py runserver时UnicodeDecodeError的原因与解决方案
人工智能·python·chatgpt·中间件·django·utf8
是Dream呀35 分钟前
2025年中秋月亮只有94.91%圆?Python告诉你真相
开发语言·python·中秋节
星辰徐哥36 分钟前
Python开发从入门到精通:异步编程与协程
开发语言·python