【问题标题】:Response Headers Empty响应标头为空
【发布时间】:2019-12-02 17:54:44
【问题描述】:

我正在制作一个聊天应用程序。我有以下问题:当我向服务器发送请求时,响应不包含任何标头。我想检查令牌的某个标头,但该标头为空。

当我使用邮递员时,我在标题中看到了令牌。但是,当我在 javascript 中使用 fetch api 时,我看到了 header 但里面的 header 是空的。我还在谷歌开发者工具中看到了标题。

我认为,这与 CORS 无关。

static async userLogin(username,password){

    const url = `http://localhost:9090/api/authenticate?username=${username}&password=${password}`;

    await fetch(url,{
        method: "GET",
    }).then(response => console.log(response));

}

【问题讨论】:

  • 您遇到了 CORS。您的前端应用程序必须与后端 API 服务器位于不同的域中。在这种情况下,CORS 只允许设置特定的标头。检查此链接以更好地理解 - developer.mozilla.org/en-US/docs/Web/HTTP/…
  • 这是我的cors配置功能。如果错了,我不应该在开发者工具中看到令牌CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(Arrays.asList("*")); configuration.setAllowedMethods(Arrays.asList("GET","POST")); configuration.addAllowedHeader("*"); configuration.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration);
  • 好的。如果您说您可以在开发人员工具中看到标题,但在代码中看不到。尝试使用res.headers.get('header_key')

标签: javascript java reactjs


【解决方案1】:

对于遇到相同问题的其他人,请使用Access-Control-Expose-Headers,它允许服务器将允许浏览器中的 Javascript(例如 getResponseHeader())访问的标头列入白名单。

即使在我使用fetch 和切换到XMLHttpRequest 并使用getResponseHeaders() 时,response.headers 还是空的,它仍然有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-26
    • 2019-06-20
    • 2015-01-24
    • 2011-09-30
    • 2016-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多