2017-11-25 156 views
0

我在axios GET請求中設置授權標頭時遇到問題。 我做了很多研究,但沒有找到解決辦法。此外,我檢查了CORS設置,它應該是正常的,並且請求是從郵遞員或預先休息客戶端工作的,所以我不相信這是服務器端的問題。Axios不發送授權標頭 - ReactJS

我與愛可信的請求

export function getUserInfo (userId) { 
    return function (dispatch) { 
    axios.get(`${ROOT_URL}/user/${userId}`, helperMethods.authorizedHeader()) 
    .then(response => { 
     dispatch({type: USER_INFO, payload: response.data.message}); 
    }) 
    .catch(error => { 
     console.log('something went wrong: ', error); 
    }); 
    }; 
} 

Helper方法函數(它返回有效的對象,我調試它)

export function authorizedHeader() { 
    let token = sessionStorage.getItem(TOKEN); 
    if (!token) { 
    token = localStorage.getItem(TOKEN); 
    } 
    return { 
    headers: { 
    'Accept': 'application/json', 
    'Authorization': `${token}` 
    } 
}; 
} 

而且CORS設置:

@Bean 
public CorsFilter corsFilter() { 
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 
    CorsConfiguration config = new CorsConfiguration(); 
    config.setAllowCredentials(true); 
    config.addAllowedOrigin("*"); 
    config.addAllowedHeader("*"); 
    config.addAllowedMethod("*"); 
    source.registerCorsConfiguration("/**", config); 
    return new CorsFilter(source); 
} 

所以,如果你有任何建議請與我分享。

謝謝

回答

0

最後,我發現了這個問題。問題出在我服務器端的CORS配置上。當請求被觸發時,它首先進入彈簧CORS過濾器,這是拒絕請求,並且它從不觸發我的CORS過濾器。 所以我要設置觸發,類似的東西的順序:

FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); 
    bean.setOrder(-110); 

這裏是整個更新CORS配置:

@Bean 
public FilterRegistrationBean platformCorsFilter() { 
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 

    CorsConfiguration configAutenticacao = new CorsConfiguration(); 
    configAutenticacao.setAllowCredentials(true); 
    configAutenticacao.addAllowedOrigin("*"); 
    configAutenticacao.addAllowedHeader("Authorization"); 
    configAutenticacao.addAllowedHeader("Content-Type"); 
    configAutenticacao.addAllowedHeader("Accept"); 
    configAutenticacao.addAllowedMethod("POST"); 
    configAutenticacao.addAllowedMethod("GET"); 
    configAutenticacao.addAllowedMethod("DELETE"); 
    configAutenticacao.addAllowedMethod("PUT"); 
    configAutenticacao.addAllowedMethod("OPTIONS"); 
    configAutenticacao.setMaxAge(3600L); 
    source.registerCorsConfiguration("/**", configAutenticacao); 

    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); 
    bean.setOrder(-110); 
    return bean; 
}