前端無法獲取後端自定義的請求頭

問題:前端可以接收到請求但是無法獲取自定義Header的token

解決
在SpringBoot中配置如下

@Configuration
public class CORSConfiguration implements WebMvcConfigurer {
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true); /*是否允許請求帶有驗證信息*/
        corsConfiguration.addAllowedOrigin("*");/*允許訪問的客戶端域名*/
        corsConfiguration.addAllowedHeader("*");/*允許服務端訪問的客戶端請求頭*/
        corsConfiguration.addAllowedMethod("*"); /*允許訪問的方法名,GET POST等*/
        corsConfiguration.addExposedHeader("token");/*暴露哪些頭部信息 不能用*因爲跨域訪問默認不能獲取全部頭部信息*/
        corsConfiguration.addExposedHeader("Authorization");
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章