前后端分离模式下跨域解决方案

1.后端服务开启跨域

//第一种
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedHeaders(CorsConfiguration.ALL)
                .allowedMethods(CorsConfiguration.ALL)
                .allowCredentials(true)
                .maxAge(3600); // 1小时内不需要再预检(发OPTIONS请求)
    }
}
//第二种
@Configuration
public class CorsConfig {
 
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true); //支持cookie 跨域
        config.setAllowedOrigins(Arrays.asList("*"));
        config.setAllowedHeaders(Arrays.asList("*"));
        config.setAllowedMethods(Arrays.asList("*"));
        config.setMaxAge(300L);//设置时间有效
 
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

2.nginx开启跨域

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on; 
    keepalive_timeout  65;

    server {
                
        listen       80;
        server_name  localhost;
        #这里2种写法
                add_header Access-Control-Allow-Credentials true;
                add_header Access-Control-Allow-Origin $http_origin;
                #add_header "Access-Control-Allow-Origin" "*"; #允许来自所有的访问地址
                #add_header "Access-Control-Allow-Methods" "GET, PUT, POST, DELETE, OPTIONS"; #支持请求方式
                
                location = / {
            root   html;
            index  index.html index.htm;
        }
    }
}

总结:

1.前端配置跨域 无论后台及nginx 配不配 都可以跨域

2.后台配置跨域 或nginx 配置跨域 前台不配  都可以跨域

3.后台与 nginx 同时配置跨域 前台不配 不可以跨域

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值