[SpringBoot] 跨域

kingdelee發表於2019-08-06

跨域解釋:
https://blog.csdn.net/qinaye/article/detai...

參考:
https://segmentfault.com/a/119000001855452...
https://blog.csdn.net/zhaokejin521/article...

package com.hbshunjie.guache.config.mvc;

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 GlobalCorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        //1.新增CORS配置資訊
        CorsConfiguration config = new CorsConfiguration();
          //放行哪些原始域
          config.addAllowedOrigin("*");
          //是否傳送Cookie資訊
          config.setAllowCredentials(true);
          //放行哪些原始域(請求方式)
          config.addAllowedMethod("*");
          //放行哪些原始域(頭部資訊)
          config.addAllowedHeader("*");
          //暴露哪些頭部資訊(因為跨域訪問預設不能獲取全部頭部資訊)
//          config.addExposedHeader("*");

        //2.新增對映路徑
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);

        //3.返回新的CorsFilter.
        return new CorsFilter(configSource);
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章