【问题标题】:Can't get response from axios POST request (React)无法从 axios POST 请求中获得响应(React)
【发布时间】:2022-01-08 03:07:18
【问题描述】:

我正在尝试从这个 axios 请求中获取响应头:

     const res = await axios.post(process.env.REACT_APP_URL_API + "/login", {
                username: userRef.current.value,
                password: passwordRef.current.value,
            }).then(response => console.log(response.headers))

状态为 200,我收到了 2 个响应

“OPTIONS”,据我阅读,他与 CORS 政策有关

CHROME response OPTIONS

和 POST 响应,带有我需要的标头(凭据、JWT 和所有)

CHROME response POST

这是我的问题:在 axios response 中,我得到的 OPTIONS 标头希望是无用的,我不知道如何访问 POST 中的“真实”数据,我该如何解决这个问题?

【问题讨论】:

  • 如果您使用的是. then(),则不应使用await

标签: reactjs post axios


【解决方案1】:

已解决

最后是后端(Spring)CORS 配置问题,我没有配置正确的标头可见性。

CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    List<String> allowOrigins = Arrays.asList("*");
    configuration.setAllowedOriginPatterns(allowOrigins);
    configuration.setAllowedMethods(singletonList("*"));
    configuration.setAllowedHeaders(singletonList("*"));
    //Adding following line made the required headers visible in frontend
    configuration.setExposedHeaders(List.of("Authorization", "Role", "Username"));
    configuration.setAllowCredentials(true);
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 2022-01-17
    • 2013-04-02
    • 2020-07-07
    • 1970-01-01
    相关资源
    最近更新 更多