SpringBoot跨域(cors)解决方案

编写CorsConfig配置类

package com.psyduck.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;

@Configuration
public class CorsConfig {
    
    
    public CorsConfig(){
    
    

    }

    @Bean
    public CorsFilter corsFilter(){
    
    
        //1.添加Cors配置信息
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("http://localhost:8080"); //设置允许跨域访问服务端的客户端地址
        corsConfiguration.addAllowedMethod(CorsConfiguration.ALL);//设置允许的请求方式
        corsConfiguration.addAllowedHeader(CorsConfiguration.ALL);//设置访问哪些请求头
        corsConfiguration.setAllowCredentials(true);//允许携带cookie跨域
        //2.为URL添加映射路径
        UrlBasedCorsConfigurationSource ubccs = new UrlBasedCorsConfigurationSource();
        ubccs.registerCorsConfiguration("/**",corsConfiguration);
        //3.返回重新定义好的corsfilter
        return new CorsFilter(ubccs);
    }
}

直接在Controller层加注解

package com.psyduck.controller;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.cors.CorsConfiguration;
import springfox.documentation.annotations.ApiIgnore;

@CrossOrigin(
        origins = {
    
    "允许跨域访问服务端的客户端地址A","允许跨域访问服务端的客户端地址B"},
        methods = {
    
    RequestMethod.GET,RequestMethod.POST},
        allowedHeaders ="*",
        allowCredentials = "true",
        maxAge = 2400 //跨域响应前缓存可以存在的最大时间 单位为秒
        )
@ApiIgnore
@RestController
public class HelloController {
    
    

    @GetMapping("/hello")
    public Object Hello(){
    
    
        return "Hello World";
    }

}

一些注意的点

CorsConfiguration.ALL这个常量可以用 ∗ \boldsymbol{*} 代替

当origins = "*"时,不能允许携带cookie和session跨域,也就是allowCredentials不能为true,否则会出现多次跨域使用同一个session的问题。

此注解也可以用在方法上

当设置允许携带cookie和session跨域时,前端需要设置withCredentials: true

通常2种解决方案混用,分别做大范围和精细控制。

最后更新于2021年3月2日
原创不易,如果该文章对你有所帮助,望左上角点击关注~如有任何技术相关问题,可通过评论联系我讨论,我会在力所能及之内进行相应回复以及开单章解决该问题.

该文章如有任何错误请在评论中指出,感激不尽,转载请附出处!
*个人博客首页:https://blog.csdn.net/yjrguxing ——您的每个关注和评论都对我意义重大

猜你喜欢

转载自blog.csdn.net/yjrguxing/article/details/114298887
今日推荐