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 ——您的每个关注和评论都对我意义重大

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值