Spring Boot Web 项目配置解决跨域

文章归档:https://www.yuque.com/u27599042/coding_star/xc80n6opewy92kfp

通过编写配置类实现 WebMvcConfigurer 接口解决跨域

在项目中增加 WebMvcConfigurer 接口的实现配置类 WebMvcConfig

java 复制代码
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Web MVC 配置类
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    /**
     * 配置解决跨域
     *
     * @param corsRegistry 跨域注册对象
     */
    @Override
    public void addCorsMappings(CorsRegistry corsRegistry) {
        corsRegistry
                // 配置哪些请求路径允许跨域
                .addMapping("/**")
                // 是否发送 Cookie
                .allowCredentials(true)
                // 允许跨域的请求来源,设置 Access-Control-Allow-Origin
                .allowedOriginPatterns("*")
                // 允许跨域的请求方法类型
                .allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"})
                // 允许跨域的请求头信息,设置 Access-Control-Allow-Headers
                .allowedHeaders("*")
                // 暴露的头信息,设置 Access-Control-Expose-Headers,默认空
                .exposedHeaders("*");
    }
}
相关推荐
想不到一个好的ID11 小时前
Redis Cluster
后端
EatFan11 小时前
Spring Boot 4.0 升级清单:JDK 基线、Jakarta 命名空间、Observation API 与第三方组件兼容一次讲清
java·spring boot·后端
大大大大晴天11 小时前
从System.out到可观测性:Java 日志框架的演进与选型
后端
辰海Coding12 小时前
平台如何接入一台物联网设备?又该如何设计它的通信协议?
java·物联网
代码民工正电荷12 小时前
JAVA重要知识点和集合
java·开发语言
李少兄13 小时前
IDEA Apifox Helper 插件踩坑:2.0.15-243 版本“导出指定接口”参数描述丢失问题解析与修复方案
java·ide·intellij-idea
JavaGuide13 小时前
Gemini 杀疯了,反重力给我用爽了!分享 8 个 Antigravity 使用技巧
人工智能·后端
努力攀登的小k14 小时前
《新手练表:从建表到删表全操作|从零学会表操作》
java·数据库·mysql
想不到一个好的ID14 小时前
Redis 哨兵(Sentinel)
后端
Yetian_200014 小时前
Postman测试上传图片文件接口
java·postman