跨源资源共享 (CORS)(或通俗地译为跨域资源共享)是一种基于 HTTP 头的机制,该机制通过允许服务器标示除了它自己以外的其它 origin(域,协议和端口),使得浏览器允许这些 origin 访问加载自己的资源。跨源资源共享还通过一种机制来检查服务器是否会允许要发送的真实请求,该机制通过浏览器发起一个到服务器托管的跨源资源的"预检"请求。在预检中,浏览器发送的头中标示有 HTTP 方法和真实请求中会用到的头。
跨源 HTTP 请求的一个例子:运行在 https://domain-a.com 的 JavaScript 代码使用 XMLHttpRequest 来发起一个到 https://domain-b.com/data.json 的请求。
关于CORS知识查看之前的文章。
SpringBoot解决CORS跨域请求:https://blog.csdn.net/qq_42402854/article/details/109216343
前端页面 html代码:
DOCTYPE html>
Title
function getData() {
$.get('http://localhost:18088/app-api/app-user/user/getRequestParameter/1?token=abc123',function(data){
alert(data);
});
}
直接双击它浏览器打开,点击 触发按钮(访问 Gateway服务统一入口API)报跨域错误。
通过 Gateway解决 CORS跨域问题也非常简单。
“全局”CORS配置是URL模式到 Spring Framework CorsConfiguration的映射。
官方文档:https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#cors-configuration
Gateway网关有两种配置方式:
- 通过 YAML配置
- 通过 Java配置类配置
spring:
application:
name: app-gateway
#配置 nacos注册中心
cloud:
nacos:
discovery:
server-addr: 192.168.xxx.xxx:8848
#配置 gateway网关
gateway:
# CORS跨越配置
globalcors:
cors-configurations:
'[/**]':
allowedOrigins: "*" # 开发环境设置为*,生产环境设置为域名
allowedMethods:
- GET
- OPTION
- POST
- DELETE
- PUT
#设置路由:路由id、路由到微服务的uri、断言
重启 Gateway服务,重新点击 触发按钮,访问 OK。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;
/**
* CORS跨越配置
*/
//@Configuration
public class AppCorsConfig {
@Bean
public CorsWebFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
// 开发环境设置为*
config.addAllowedMethod("*");
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}
}
– 求知若饥,虚心若愚。