【跨域系】为何配置了corsFilter还是出现跨域问题
在描述这个问题之前,我这里先声明下自己使用的spring-web的版本是5.2.4.RELEASE
关于为啥会出现跨域,这里就不在详细介绍,因为这个问题网上一大堆资料。一般需要解决跨域这个问题,都是通过后端来解决 java代码或者nginx来处理
java代码解决这个问题,尤其是springboot项目,可以有很多种方式,我这里由于项目原因以及处于从web访问执行的流程上来说filter肯定是先执行的,直接就选择用filter来处理的。这里贴上代码配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import java.time.Duration;
/**
* 添加支持跨域
*/
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsFilter corsFilter() {
//1. 添加 CORS配置信息
CorsConfiguration config = new CorsConfiguration();
//放行哪些原始域
config.addAllowedOrigin("*");
//是否发送 Cookie
config.setAllowCredentials(true);
//放行哪些请求方式
config.addAllowedMethod("*");
//放行哪些原始请求头部信息
config.addAllowedHeader("*");
config.setMaxAge(Duration.ofHours(6));
config.addExposedHeader("Content-Type");
config.addExposedHeader("X-Requested-With");
config.addExposedHeader("accept");
config.addExposedHeader("Origin");
config.addExposedHeader("Access-Control-Request-Method");
config.addExposedHeader("Access-Control-Request-Headers");
//2. 添加映射路径
UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
corsConfigurationSource.registerCorsConfiguration("/**", config);
//3. 返回新的CorsFilter
return new CorsFilter(corsConfigurationSource);
}
}
贴上上面的代码,理论上面springboot启动 之后,跨域问题应该就可以解决了,但是当我访问的时候还是会出现跨域的问题
为了本地容易测试这个跨域问题,简单写了一个简单的html文件贴到这里来,当然关于页面需要的脚本jquery包 就大家需要自己来获取了
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>
跨域jquery脚本
</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta name="keywords" content="跨域jquery脚本">
<meta name="description"content="跨域jquery脚本">
<meta http-equiv="Cache-Control" content="no-transform">
<meta name="renderer" content="webkit">
<meta name="screen-orientation" content="portrait">
<meta name="x5-orientation" content="portrait">
<meta name="format-detection" content="telephone=no,email=no,adress=no">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<script src="./jquery.js"></script>
<script>
$(function(){
$('#corsBtn').click(function(){
$.ajax({
type: "POST", //提交的方法
xhrFields: { withCredentials: true },
crossDomain:true,
url: "http://localhost:8582/poOrderWeChatController/query", //接口地址
async: false,//false同步,true异步
dataType: 'json',
contentType: 'application/x-www-form-urlencoded',
data: {
"createTimeFrom":"2022-10-25 00:00:00",
"createTimeTo":"2023-11-23 23:59:59"
},
error: function (request) { //失败
alert("Connection error");
},
success: function (data) { //成功
alert(data); //就将返回的数据显示出来
}
});
});
$('#corsBtn2').click(function(){
let formData ={
"operation": "2222",
"orderCheckDataList": [{
"coordinationFlag": "N",
"poNo":"233333",
"orderType": "33333"
}
]
};
$.ajax({
type: "POST", //提交的方法
url: "http://localhost:8582/poOrderWeChatController/examine", //接口地址
async: false,//false同步,true异步
dataType: 'json',
xhrFields: { withCredentials: true },
contentType: "application/json;",
data: JSON.stringify(formData),
error: function (request) { //失败
alert("Connection error");
},
success: function (data) { //成功
alert(data); //就将返回的数据显示出来
}
});
});
});
</script>
</head>
<body>
<button id='corsBtn' style = "width:200px;height:60px"> form表单点击跨域请求</button>
<button id='corsBtn2' style = "width:200px;height:60px">json提交点击跨域请求</button>
</body>
</html>
通过浏览器打开之后,就可以访问对应的页面,点击跨域按钮就测试对应的接口,是否支持跨域通过f12控制台就可以查看到
虽然添加了跨域的配置,这里我的控制台竟然是跨域的问题。怎么来排查问题呢
我这边直接在项目中corsFilter debug了下,结果没有进来。
这里顺便提一句,我们需要进入断点的是spring包下面的corsFilter,而不是tomcat下面的这个类
为什么没有进来呢?难道是项目中其他的过滤器直接返回出去了,还没有执行corsFilter。顺着这个思路我看到了项目中确实存在一个filter 直接返回出去,不走下面的过滤器链了。
于是我这边就想着将跨域的过滤器优先级高点让它先去执行,顺着这个思路。我添加了下面的代码
@Bean
public FilterRegistrationBean corsFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(corsFilter);
registration.addUrlPatterns("/*");
registration.setName("corsFilter");
registration.setOrder(-99999);
return registration;
}
重启项目后,果然跨域的debug进来了,确实也实现了允许跨域的功能
分类:
异常记录
标签:
java
, springboot
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步