我正在尝试使用XMLHttpRequest从服务器获取授权令牌,但仅返回一些标头(不包含Authorization标头)。 服务器在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);
当我尝试获取所有标头时,我只获得其中的一些标头(例如缓存控制,内容长度,过期,编译指示),而没有Authorization标头和其他标头。我应该改变以获得所有这些?感谢您的任何帮助。 enter image description here
答案 0 :(得分:-1)
我设法通过在服务器站点上设置暴露的标头来解决此问题:
configuration.setExposedHeaders(Arrays.asList("Authorization, X-Content-Type-Options, " +
"X-XSS-Protection, Cache-Control, Pragma, Expires, X-Frame-Options, Content-Length, Date"));