【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

本文完结!

相关推荐
chao_7895 分钟前
更灵活方便的初始化、清除方法——fixture【pytest】
服务器·自动化测试·python·pytest
心情好的小球藻35 分钟前
Python应用进阶DAY9--类型注解Type Hinting
开发语言·python
都叫我大帅哥37 分钟前
LangChain加载HTML内容全攻略:从入门到精通
python·langchain
超龄超能程序猿41 分钟前
Spring 应用中 Swagger 2.0 迁移 OpenAPI 3.0 详解:配置、注解与实践
java·spring boot·后端·spring·spring cloud
惜.己1 小时前
使用python读取json数据,简单的处理成元组数组
开发语言·python·测试工具·json
en-route1 小时前
Http请求中的特殊字符
spring·http
都叫我大帅哥2 小时前
深入浅出 Resilience4j:Java 微服务的“免疫系统”实战指南
java·spring cloud
都叫我大帅哥2 小时前
Python的Optional:让你的代码优雅处理“空值”危机
python
曾几何时`4 小时前
基于python和neo4j构建知识图谱医药问答系统
python·知识图谱·neo4j
写写闲篇儿6 小时前
Python+MongoDB高效开发组合
linux·python·mongodb