Spring Boot 和 React 应用程序中的 React DevTools 警告和 CORS 错误

问题描述 投票:0回答:1

我正在开发一个使用 Spring Boot 作为后端、React 作为前端的项目。我遇到了一些不确定如何解决的问题:

  1. React DevTools 警告:我在控制台中收到以下警告:

未知选择器在调用时返回根状态。这可能会导致不必要的重新渲染。 返回整个状态的选择器几乎肯定是一个错误,因为每当状态发生变化时,它们都会导致重新渲染。

CORS 策略错误:当尝试从我的 React 前端向 Spring Boot 后端发出请求时,我遇到了 CORS 问题:
  1. 从源“http://localhost:3000”访问“http://192.168.1.33:5001/login”处的 XMLHttpRequest(从“http://localhost:5000/api/user/profile”重定向)已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。

我已经在 Spring Boot 应用程序中配置了 CORS,但仍然收到此错误。

对于 CORS 错误:
  1. 我在 Spring Boot 后端添加了 CORS 配置,以允许来自 http://localhost:3000 的请求,这是我的 React 应用程序运行的位置。配置如下:

这是代码:

@配置 公共类 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 配置将处理跨源请求,但似乎可能缺少某些内容或配置不正确。

reactjs spring-boot redux spring-security cors
1个回答
0
投票

在 Express 或 Nest JS 中,我们执行以下操作:

cors({ 来源:“http://localhost:3000” })

© www.soinside.com 2019 - 2024. All rights reserved.