SpringBoot解决跨域的五种方式

 


Github:https://github.com/zhangzhixi0305/springboot-cross.git

Gitee:https://gitee.com/zhang-zhixi/springboot-cross.git

前端使用Nginx:http://localhost:8081

后端SpringBoot:http://localhost:8080

前端:

后端:

第一种:全局过滤器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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 MyCorsFilter {
 
    @Bean
    public CorsFilter corsFilter() {
        // 1.创建 CORS 配置对象
        CorsConfiguration config = new CorsConfiguration();
        // 支持域,格式是:域名+端口(http://localhost:8081),
        config.addAllowedOriginPattern("*");
        // 是否发送 Cookie
        config.setAllowCredentials(true);
 
        // 支持请求方式:POST,GET,HEAD等,*代表全部支持
        config.addAllowedMethod("POST");
        config.addAllowedMethod("GET");
 
        // 2.添加地址映射
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        // /** 表示当前项目的所有请求地址,都支持跨域访问。
        corsConfigurationSource.registerCorsConfiguration("/**", config);
        // 3.返回 CorsFilter 对象
        return new CorsFilter(corsConfigurationSource);
    }
}

第二种:全局MVC配置 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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 MyWebMvcConfigurer implements WebMvcConfigurer {
 
    /**
     * 全局CORS配置
     *
     * @param registry CORS注册器
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 映射服务器中那些http接口进行跨域访问
        registry.addMapping("/cors/*")
                // 配置哪些来源有权限跨域
                .allowedOrigins("http://localhost:8081")
                // 配置运行跨域访问的请求方法
                .allowedMethods("GET", "POST", "DELETE", "PUT");
    }
 
}

 

posted @   Java小白的搬砖路  阅读(3186)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具

喜欢请打赏

扫描二维码打赏

支付宝打赏

点击右上角即可分享
微信分享提示