SpringBoot 跨域配置类

跨域配置类

  • 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);
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章