同源策略:是一个安全策略。认定 (协议、域名、端口)全部相同则,认定是同源。非同源会被浏览器所拦截。

http://127.0.0.1:8080 与 http://localhost:8080 不是同源,会爆跨域

http://127.0.0.1:8080 与 https://127.0.0.1:8080 不是同源,会爆跨域

http://127.0.0.1:8080 与 http://127.0.0.1:8081 不是同源,会爆跨域

只有 http与http一致、域名与域名一致、端口与端口一致才认定为同源,就不会有问题

方式一 Java代码(常用?️)

1、启动类加上 @CrossOrigin 也可单独加在方法上,含义不言而喻

// 允许跨域
@CrossOrigin

2、配置类 CorsConfig 继承WebMvcConfigurerAdapter 重写addCorsMappings 方法

/**
 * @Author: 臧立昆
 * @Email: 740969606@qq.com
 * @Date: 2020/8/3
 * @Time: 13:47
 */

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

@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
    
    @Override
    public void addCorsMappings(CorsRegistry registry) {

        registry
                // 为指定的路径模式启用跨域请求处理
                .addMapping("/**")

                // 允许源来自*代表任何地方   Springboot 2.4 之前用.allowedOrigins("*")
                .allowedOriginPatterns("*")

                // 是否允许传递cookie,默认不允许
                .allowCredentials(true)

                // 配置允许的方法 源码注释说:GET、HEAD、POST 默认是允许的
                .allowedMethods("GET", "POST", "DELETE", "PUT", "HEAD")
                //.allowedMethods("GET", "POST", "DELETE", "PUT", "HEAD", "OPTIONS", "TRACE","CONNECT")

                // 配置客户端缓存时间(以秒为单位)默认1800秒也就是30分钟
                .maxAge(3600);

    }
}

方式二 Nginx 反向代理

Nginx 正常的反向代理 proxy_pass 可以解决跨域,非常的奇怪。

方式三 (没实际用过)

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;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {

    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",config);
        return new CorsFilter(source);
    }
}