【发布时间】:2021-07-27 09:59:08
【问题描述】:
我正在使用 springboot 和 angular。 尝试使用 JWT 登录,当使用邮递员发送 http 时,请求是可以的,但是当尝试使用 Angular 发送相同的 http 时,我得到了下一个错误:
从源访问“http://localhost:8080/login”处的 XMLHttpRequest “http://localhost:4200”已被 CORS 策略阻止:响应 预检请求未通过访问控制检查:它没有 HTTP 正常状态。
和
zone-evergreen.js:2845 POST http://localhost:8080/login 网络::ERR_FAILED
当我发送登录以外的请求时,它们工作正常 我知道需要一个 cors 所以代码是下一个:
@EnableGlobalMethodSecurity(securedEnabled = true)
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated().and().csrf().disable().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().cors();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
org.springframework.web.cors.CorsConfiguration configuration = new org.springframework.web.cors.CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
configuration.setAllowedMethods(Arrays.asList("*"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
但错误是一样的。
【问题讨论】:
-
当然,因为您的 BE 与弹簧靴的来源与角度不同。您可以在 Angular 应用程序中设置您的
proxy.conf.json
标签: java angular spring-boot cors token