SpringBoot 跨域配置类

本文详细介绍了跨域资源共享(CORS)机制及其在Web应用中的实现方式。通过Spring框架的配置,允许指定源服务器上的资源被不同域的Web应用访问。特别讲解了如何设置跨域请求的路径、源、方法及缓存时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

跨域配置类

  • import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.CorsRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    /**
     * @author Mr.Li
     * @version 1.0
     * @Description: 跨域配置类
     * @date 2020/06/13 16:51
     *
     * CORS:跨域资源共享(Cross Origin Resource Sharing)
     * 是一种机制,它使用额外的 HTTP 头来告诉浏览器让运行在一个 domain 上的 Web 应用被准许访问来自不同源服务器上的指定的资源。
     * 当一个资源从与该资源本身所在的服务器不同的域、协议或端口请求一个资源时,资源会发起一个跨域 HTTP 请求。
     *
     * 需要在跨域的方法上加上注解 @CrossOrigin
     */
    
    @Configuration
    public class WebConfig implements WebMvcConfigurer {
    
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            /**
             * addMapping(): Enable cross-origin request handling for the specified path pattern.
             * allowedOrigins(): The list of allowed origins that be specific origins, e.g.
             * allowedMethods(): Set the HTTP methods to allow.
             * maxAge(): Configure how long in seconds the response from a pre-flight request can be cached by clients.
             */
            registry.addMapping("/**")
                    .allowedOrigins("http://localhost:8081", "null")
                    // 最好先启动前端,要不然8080端口会被抢占
                    // .allowedOrigins("http://localhost:8080", "null")
                    .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                    .maxAge(3600)
                    .allowCredentials(true);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值