Spring Boot中解决跨域问题(CORS)

1. 跨域介绍

首先解释什么是跨域,跨域就是前端和后端的端口号不同;会产生跨域问题,这里浏览器的保护机制(同源策略)。
同源策略:前端和后端的协议、域名、端口号三者都相同叫做同源。
我们看一下不同源:
VUE:http://localhost:8080
Spring: http://localhost:8081/list
当我们出现跨域问题,前端就会报一个错(篮框扩这那个):
在这里插入图片描述

2. 解决方法

上方就是不同源,两者的协议、域名相同,但是端口号不同;如何解决呢,使用Spring Boot解决,它提供三种方案:

  1. 直接在方法上方添加@CrossOrigin注解即可解决问题
	@CrossOrigin
    @RequestMapping("/getuserbyid")
    public UserInfo getUserById(Integer id) {
        if(id == null ) return null;
        return userService.getUserById(id);
    }
  1. 添加 CORS 过滤器
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 {

   @Bean
   public CorsFilter corsFilter() {

       CorsConfiguration corsConfiguration = new CorsConfiguration();
       corsConfiguration.setAllowCredentials(true); // 允许cookies跨域
       corsConfiguration.addAllowedHeader("*"); // 请求头字段
       corsConfiguration.addAllowedMethod("*"); // 方法
       corsConfiguration.addAllowedOrigin("*"); // 允许向该服务器提交请求的URI,*表示全部允许,自定义可以添加多个,在SpringMVC中,如果设成*,会自动转成当前请求头中的Origin
       UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
       source.registerCorsConfiguration("/**",corsConfiguration); // 添加映射路径,以及参数


       return new CorsFilter(source);
   }
}
  1. 重写 WebMvcConfigurer 接口中的 addCorsMappings 方法


import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 先设置映射
        registry.addMapping("/**")
                .allowedOriginPatterns("*") // 允许向该服务器提交请求的URI,*表示全部允许,自定义可以添加多个,在SpringMVC中,如果设成*,会自动转成当前请求头中的Origin
                .allowCredentials(true) // 允许cookies跨域
                .allowedHeaders("*") // 请求头字段
                .allowedMethods("GET","POST") // 允许跨域的方法
                .maxAge(3600);// 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了
    }
}
  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱吃大白菜  

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值