【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

本文完结!

相关推荐
机器学习之心1 分钟前
PyTorch基于LightGBM的海洋温盐异常垂直剖面预测
人工智能·pytorch·python
Thomas.Sir5 分钟前
第十一章:RAG知识库开发之【RAG 的缺陷分析与优化:从入门到实践的完全指南】
python·ai·rag·缺陷分析·效果评估
chushiyunen6 分钟前
python web框架streamlit
开发语言·前端·python
DeepModel7 分钟前
机器学习降维核心:奇异值分解 SVD
人工智能·python·机器学习
Stack Piston7 分钟前
Spring实践@Cacheable坑
java·后端·spring
杜子不疼.10 分钟前
Spring Cloud + AI:微服务架构下的智能路由、故障自愈、日志分析
人工智能·spring cloud·架构
眷蓝天14 分钟前
python基础
开发语言·python
Ken_111523 分钟前
SpringCloud系列(59)--Nacos与其他注册中心特性对比
spring cloud
Cosmoshhhyyy23 分钟前
《Effective Java》解读第46条:优先选择Stream中无副作用的函数
java·windows·python
徽先生24 分钟前
注释标准模板
python