【问题标题】:XMLHttpRequest response doesn't return Authorization headerXMLHttpRequest 响应不返回授权标头
【发布时间】:2020-09-25 21:45:18
【问题描述】:

我正在尝试使用 XMLHttpRequest 从服务器获取授权令牌,但只返回一些标头(没有授权标头)。 服务器在 localhost:8080 上工作,但客户端应用程序在 localhost:3000 上,所以我尝试配置 CORS。

在服务器站点上我创建了一个 CorsConfigurationSource bean:

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.applyPermitDefaultValues();
    configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
    configuration.setAllowedMethods(Arrays.asList("GET","POST","DELETE","PUT"));
    configuration.setAllowCredentials(true);
    configuration.setAllowedHeaders(Arrays.asList("Authorization, X-Content-Type-Options, " +
            "X-XSS-Protection, Cache-Control, Pragma, Expires, X-Frame-Options, Content-Length, Date"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

在客户站点上我使用 XMLHttpRequest:

var httpRequest = new XMLHttpRequest();
httpRequest.open("POST", "http://localhost:8080/login", true);
httpRequest.setRequestHeader(
  "Content-Type",
  "application/json;charset=UTF-8"
);
httpRequest.setRequestHeader(
  "Access-Control-Expose-Headers",
  "Authorization"
);
httpRequest.onreadystatechange = function () {
  console.log("RESPONSE HEADER : " + httpRequest.getAllResponseHeaders());
};
httpRequest.withCredentials = true;
httpRequest.send(userBody);

当我尝试获取所有标头时,我只获得其中一些(如缓存控制、内容长度、过期、杂注)而没有授权标头和其他标头。我应该改变什么来获得所有这些?感谢您的任何帮助。 enter image description here

【问题讨论】:

    标签: xmlhttprequest cors


    【解决方案1】:

    我设法通过在服务器站点上设置公开的标头来解决这个问题:

    configuration.setExposedHeaders(Arrays.asList("Authorization, X-Content-Type-Options, " +
                        "X-XSS-Protection, Cache-Control, Pragma, Expires, X-Frame-Options, Content-Length, Date"));
    

    【讨论】:

      猜你喜欢
      • 2017-11-23
      • 2017-10-17
      • 2019-07-20
      • 2019-05-24
      • 2013-07-17
      • 2021-12-27
      • 2016-03-08
      • 2018-12-31
      • 2021-09-15
      相关资源
      最近更新 更多