【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

本文完结!

相关推荐
素玥2 分钟前
实训7 json文件数据用python导入数据库
数据库·python·json
千枫s2 分钟前
做一个电脑版爬虫程序
爬虫·python
大邳草民2 分钟前
Python 对象模型与属性访问机制
开发语言·笔记·python
weixin_402486346 分钟前
小分子 pdb准化为sdf
python
橘子编程7 分钟前
密码学完全指南:从基础到实战
java·python·密码学
蓝色的杯子7 分钟前
Python面试30分钟突击掌握-LeetCode2-Strings
python
ZC跨境爬虫9 分钟前
海南大学交友平台开发实战 day9(头像上传存入 SQLite+BLOB 存储 + 前后端联调避坑全记录)
前端·数据库·python·sqlite
FreakStudio9 分钟前
嘉立创开源:应该是全网MicroPython教程最多的开发板
python·单片机·嵌入式·大学生·面向对象·并行计算·电子diy
上天_去_做颗惺星 EVE_BLUE15 分钟前
接口自动化测试全流程:pytest 用例收集、并行执行、Allure 报告合并与上传
python·pytest
chushiyunen19 分钟前
python fastapi使用、uvicorn
开发语言·python·fastapi