SpringBoot解决跨域的方法

SpringBoot解决跨域的方法

  • 什么是跨域?
    • Url的一般格式:协议 + 域名(子域名 + 主域名) + 端口号 + 资源地址
      例如:https://www.dustyblog.cn:8080/say/Hello 是由
      https + www + dustyblog.cn + 8080 + say/Hello组成。
    • 只要协议,域名,端口号这三项组成部分中有一项不同,就可以认为是不同的域,不同的域之间互相访问资源,就被称之为跨域。
      • 域名:
          主域名不同
          http://www.baidu.com/index.html -->http://www.sina.com/index.html
          子域名不同
          http://www.666.baidu.com/index.html -->http://www.555.baidu.com/index.html
          域名和域名ip
          http://www.baidu.com/index.html -->http://180.149.132.47/index.html
      • 端口:
          http://www.baidu.com:8080/index.html–> http://www.baidu.com:8081/index.html
      • 协议:
          http://www.baidu.com:8080/index.html–> https://www.baidu.com:8080/test.js
      • 备注:
        端口和协议的不同,只能通过后台来解决
        localhost和127.0.0.1虽然都指向本机,但也属于跨域
  • 跨域的解决
    • @Configuration启动容器+@Bean注册Bean
      @Configuration
      public class CorsConfig {
          @Bean
      	public CorsFilter corsFilter() {
      		final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
      		final CorsConfiguration cors = new CorsConfiguration();
      		cors.setAllowCredentials(true);
      		cors.addAllowedOrigin("*");
      		cors.addAllowedHeader("*");
      		cors.addAllowedMethod("*");
      		urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", cors);
      		return new CorsFilter(urlBasedCorsConfigurationSource);
      	}
      }
      
    • 继承WebMvcConfigurationSupport,这种方式也会在容器初始化的时候触发addCorsMappings(CorsRegistry registry)方法。
      @Configuration
      public class CorsConfig extends WebMvcConfigurationSupport {
      	@Override
      	public void addCorsMappings(CorsRegistry registry) {
      		super.addCorsMappings(registry);
      		registry.addMapping("/**")
              		.allowedMethods("*")
              		.allowedOrigins("*")
              		.allowedHeaders("*");
              		.maxAge(3600)
              		.allowCredentials(true);
      	}
      }
      
    • @CrossOrigin注解
      • 加在controller方法/类上,指定访问源
        @CrossOrigin(origins = {"*","null"},allowCredentials="true", maxAge = 3600)
        // origins:允许可访问的域列表。
        // maxAge:准备响应前的缓存持续的最大时间(以秒为单位)。
        @RestController
        @RequestMapping("/user")
        public class TestController {
        
        }
        
      • 加在controller方法上
        	@CrossOrigin
            @PostMapping("/insertDept")
        	@ApiOperation(value = "新增部门")
        	public String insertDept(@MultiRequestBody Dept dept) {
        	
        	}
        
      参考链接: springboot下跨域解决的四种方法
      参考链接:springboot 跨域的四种方式
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值