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