我正在开发一个使用 Spring Boot 作为后端、React 作为前端的项目。我遇到了一些不确定如何解决的问题:
未知选择器在调用时返回根状态。这可能会导致不必要的重新渲染。 返回整个状态的选择器几乎肯定是一个错误,因为每当状态发生变化时,它们都会导致重新渲染。
CORS 策略错误:当尝试从我的 React 前端向 Spring Boot 后端发出请求时,我遇到了 CORS 问题:我已经在 Spring Boot 应用程序中配置了 CORS,但仍然收到此错误。
对于 CORS 错误:
这是代码:
@配置 公共类 AppConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity.sessionManagement(managment -> managment.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(
Authorize -> Authorize.requestMatchers("/api/**").authenticated().anyRequest().permitAll())
.addFilterBefore(new JwtTokenValidator(), BasicAuthenticationFilter.class)
.csrf(csrf -> csrf.disable())
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
.httpBasic(Customizer.withDefaults())
.formLogin(Customizer.withDefaults());
return httpSecurity.build();
}
private CorsConfigurationSource corsConfigurationSource() {
return new CorsConfigurationSource() {
@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
CorsConfiguration cfg = new CorsConfiguration();
cfg.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
cfg.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "HEAD"));
cfg.setAllowCredentials(true);
cfg.setAllowedHeaders(Collections.singletonList("*"));
cfg.setExposedHeaders(Arrays.asList("Authorization"));
cfg.setMaxAge(3600L);
return cfg;
}
};
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
我的期望
对于 CORS 错误:我希望 Spring Boot 后端允许来自 React 前端的请求,而不会出现任何 CORS 问题,尤其是在添加 CORS 配置之后。我预计 CORS 配置将处理跨源请求,但似乎可能缺少某些内容或配置不正确。
在 Express 或 Nest JS 中,我们执行以下操作:
cors({ 来源:“http://localhost:3000” })