我正在尝试使用基本身份验证来保护使用服务器API获取的图像,并且在将图像加载到视图中时出现错误。
<head>
<script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://myurl.com", true);
xhr.withCredentials = true;
xhr.setRequestHeader("Authorization", 'Basic ' + btoa('test:test123'));
xhr.onload = function () {
console.log(xhr.responseText);
};
xhr.send();
</script>
</head>
<div id="image" style="width: 430px; height: 430px;"></div>
and i am getting below error.
Response for preflight is invalid (redirect)
答案 0 :(得分:0)
浏览器在初始请求完成之前向服务器发送OPTIONS调用。 它正在检查是否允许你进行这个调用,如果这个调用/端点存在,还有几个这样的事情。
同时检查:https://www.html5rocks.com/static/images/cors_server_flowchart.png
如果您使用的是Spring Boot,则应在CORS配置中允许OPTIONS调用。 示例:
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic()
.and()
.cors().configurationSource(corsConfigurationSource())
.and()
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS).permitAll() // allow CORS option calls
.antMatchers("/**").permitAll();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("*"));
configuration.setAllowedHeaders(Arrays.asList("*"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}