filter导致跨域失效_Springboot 拦截器导致 @CrossOrigin 跨域失效的解决方案

原因:

CROS 复杂请求时会首先发送一个 OPTIONS 请求做嗅探,来测试服务器是否支持本次请求,请求成功后才会发送真实的请求;而 OPTIONS 请求不会携带数据,导致这个请求被拦截了,直接返回了状态码,响应头中没携带解决跨域问题的头部信息,出现了跨域问题。

方法一:

因此解决方案是把所有的 OPTIONS 请求统统放行。详细分析见:https://blog.csdn.net/MrKorbin/article/details/104066979

在 preHandle 加以下内容:

if("OPTIONS".equals(request.getMethod().toUpperCase())) {

return true;

}

方法二:

不使用 @CrosOrigin 注解解决跨域问题,使用过滤器:示例使用 CorsFilter,也就是一个封装了解决跨域问题的 filter 而已。

package com.pacmp.config;

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;

/**

* @Author

* @Date 2020/6/19 15:48

* @Version 版本号

* @Description 描述

*/

@Configuration

public class GlobalCorsConfig {

@Bean

public CorsFilter corsFilter() {

CorsConfiguration config = new CorsConfiguration();

config.addAllowedOrigin("*");

config.setAllowCredentials(true);

config.addAllowedMethod("*");

config.addAllowedHeader("*");

UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();

configSource.registerCorsConfiguration("/**", config);

return new CorsFilter(configSource);

}

}

推荐阅读

GitHub 下载神器强势回归!

巧用枚举来干掉if-else,代码更优雅!

如何正确访问Redis中的海量数据?服务才不会挂掉!

超硬核!1.6W 字 Redis 面试知识点总结,建议收藏!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值