【跨域系】为何配置了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进来了,确实也实现了允许跨域的功能

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值