SpringBoot前后端分离解决跨域

213 阅读2分钟

一、什么是跨域

在前端领域中,跨域是指浏览器允许向服务器发送跨域请求,从而克服Ajax只能同源使用的限制。

1.1 什么是同源策略

所谓同源是指"协议+域名+端口"三者相同,  即便两个不同的域名指向同一个ip地址,也非同源。

1.2. 同源策略限制以下几种行为

  • Cookie、LocalStorage 和 IndexDB 无法读取
  • DOM和JS对象无法获得
  • AJAX 请求不能发送,说的更直白一点,就是我们在前端使用AJAX 发送异步请求,如果这个请求的URL地址与当前地址栏中的URL地址协议不同、域名不同、端口不同时,都称为跨域

二、常见的跨域场景

image.png

三、跨域问题的解决策略

CROS(Cross Origin Resource Sharing)策略,全称为跨域资源共享策略,是后端用来解决跨域问题的一个方案。

四、解决方法

1.@CrossOrigin注解

在后端接口方法上添加@CrossOrigin注解,可以解决对这个接口方法的请求跨域问题,但是在实际开发中一般都会有很多的方法,在每一个方法上都添加这个注解的话明显就会很影响使用感受。当然还可以将注解添加到类上,表示类中的所有方法都解决了跨域问题,但是类也不止一个还是麻烦。

@CrossOrigin
@GetMapping("/请求名")
public String sayHello() {
    return "hello world !";
}

2.使用过滤器统一处理

// 对比着看,包千万别导错了
import org.springframework.context.annotation.Bean;
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.addAllowedOrigin("*");
        // 使用通配符* 允许所有请求头字段
        corsConfiguration.addAllowedHeader("*");
        // 使用通配符* 允许所有请求头方法类型
        corsConfiguration.addAllowedMethod("*");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 处理请求映射
        source.registerCorsConfiguration("/**", corsConfiguration);
        
        return new CorsFilter(source);
    }
}

3.使用WebMvc的配置类

// 对比着看,包千万别导错了
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 WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")      // 设置映射
                .allowedOriginPatterns("*")        // 设置域
                .allowedMethods("*")               // 设置请求的方式GET、POST等
                .allowCredentials(true)            // 设置是否携带cookie
                .maxAge(3600)                      // 设置设置的有效期 秒单位
                .allowedHeaders("*");              // 设置头
    }
}