本地主机不同端口上的 React 应用程序和 Spring Boot 应用程序

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

我的 ReactJS(frontend) 登录页面在 localhost:3000 中运行,我的后端代码在 java springboot(backend) localhost:8080 中验证客户。 当我从前端到后端进行 api 调用时,我遇到了跨源问题,

  1. 解决本地主机中的跨源问题后它可以工作吗?
  2. 在本地主机中使用不同端口进行开发测试是否是一种好的做法?

No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled

java reactjs spring-boot
1个回答
0
投票

是的,解决跨源问题后就可以了,只需在你的springboot中添加cores配置类即可。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfigReact{
@Bean
public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new 
UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.addAllowedOrigin("http://localhost:3000");
    config.addAllowedMethod("*");
    config.addAllowedHeader("*");
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}
}
© www.soinside.com 2019 - 2024. All rights reserved.