Java / Spring
IntelliJ와 VSCode HTTP 통신 구현 본문
인텔리제이를 사용하여 스프링부트의 내부 서버를 구현하고 REST API 통신을 위해 vscode 로 구현한 로그인 데이터를 백엔드 서버로 요청을 보내고 응답을 받는 테스트를 진행하였다. 나중에도 많이 사용하고 기본적으로 알고 있어야 될 내용이라고 생각해서 기록을 하기로 하였다.
먼저, 프로젝트 구조 상 별도의 webconfig 를 구현할 필요 없이 Spring Security 를 사용하고 있기에 이미 구현해놓은 SecurityConfig 라는 클래스 내부에 백엔드 서버에서 데이터를 보낼 프론트엔트 PORT 번호를 설정한다.
스프링 컨테이너에 등록한 아래의 클래스 내부 CorsConfigurationSource() 메서드 내부에 정보를 입력해준다.
(프론트엔드 PORT 번호 : localhost:3000 )
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Collections.singletonList("http://localhost:3000")); // 허용할 Origin
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS")); // 허용할 HTTP 메서드
configuration.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type")); // 허용할 헤더
configuration.setExposedHeaders(Arrays.asList("Authorization"));
configuration.setAllowCredentials(true); // 쿠키 허용 여부
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration); // 모든 경로에 대해 CORS 설정 적용
return source;
}
위의 설정이 완료되면 반대로 vscode 에서도 main.js 에 아래의 서버에서 보낼 base URL을 즉, PORT 번호 설정을 한다.
테스트를 진행 해보면
스크립트 내부에서 axios 를 통해 Security 에서 설정한 url 주소를 입력하고 로그인 페이지에서 ID 와 Password 를 입력하면 정상적으로 HTTP 통신이 가능해진다.