【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

本文完结!

相关推荐
QQ2422199793 小时前
基于python+微信小程序的家教管理系统_mh3j9
开发语言·python·微信小程序
RSTJ_16253 小时前
PYTHON+AI LLM DAY THREETY-SEVEN
开发语言·人工智能·python
郝学胜-神的一滴3 小时前
深度学习优化核心:梯度下降与网络训练全解析
数据结构·人工智能·python·深度学习·算法·机器学习
Aision_3 小时前
Agent 为什么需要 Checkpoint?
人工智能·python·gpt·langchain·prompt·aigc·agi
清水白石0083 小时前
《Python性能深潜:从对象分配开销到“小对象风暴”的破解之道(含实战与最佳实践)》
开发语言·python
nj01284 小时前
Spring 循环依赖详解:三级缓存、早期引用、AOP 代理与懒加载
java·spring·缓存
Land03294 小时前
RPA工具选型技术指南:架构差异与实测数据
python·自动化·rpa
kafei_*5 小时前
VScode 添加 UV虚拟环境方法
vscode·python·uv
洛_尘5 小时前
Python 5:使用库
java·前端·python
m0_596749096 小时前
如何防止SQL拼接漏洞_使用PDO对象实现安全的SQL交互
jvm·数据库·python