[SPRING] React, Spring API 연동

.·2025년 1월 7일

SPRING

목록 보기
10/15

서로 다른 포트 간 API 연결을 수행해보자.

1. React - axios API 요청

import axios from "axios";
import { useEffect, useState } from "react";


const Visualization = () => {

  const [content, setContent] = useState();

  useEffect(() => {
    axios.get('/vis/hello')
          .then(res => setContent(res.data));
  });

    return (
      <h2>내용: {content}</h2>
    )
};

export default Visualization;

프론트에서 /vis/hello라는 URL로 API를 요청하여 받아온 데이터를 화면에 넣어주는 코드이다.

2. Spring - RestController 응답

package com.example.test.visualization.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/vis")
public class VisController {

    @GetMapping("/hello")
    public String test() {
        return "Hello, world!";
    }
}

그러면 요청 URL에 맞게 Controller 메소드가 작동하여 데이터를 리턴해준다.

이때 요청하는 포트와 응답하는 포트가 다르므로 추가 설정이 필요하다.

3. React - proxy 설정

package.json 파일에 다음 설정을 추가해준다.

"proxy": "http://localhost:8080"

이 설정은 React 개발 서버에서 API 요청을 보낼 때, http://localhost:8080을 통해 요청을 프록시하는 것이다.

프록시(Proxy)는 클라이언트(사용자 또는 프로그램)와 서버 간의 중계자 역할을 한다.
클라이언트가 서버에 직접 요청을 보내지 않고, 프록시 서버를 거쳐 요청을 전달하고 응답을 받는다.

클라이언트가 http://localhost:3000/api/data에 요청을 보내면, 프록시는 이를 http://localhost:8080/api/data로 리다이렉트하는 역할을 한다.

4. Spring - WebConfig 설정

WebConfig 파일을 생성하여 몇가지 설정을 해준다.

package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                // 모든 API 경로에 CORS 설정
                registry.addMapping("/**") // /** 모든 경로에 적용
                        .allowedOrigins("http://localhost:3000") // 허용할 Origin
                        .allowedMethods("GET", "POST", "PUT", "DELETE") // 허용할 메서드
                        .allowCredentials(true); // 쿠키 허용
            }
        };
    }
}

이 메서드는 CORS 정책을 설정하는 메서드이다.

CORS

CORS는 Cross-Origin Resource Sharing의 약자로, 브라우저에서 다른 출처(Origin)에 있는 리소스에 접근할 때의 규칙을 정의하는 메커니즘이다.
이를 통해 보안과 데이터 보호를 보장하면서도 특정 조건에서만 다른 도메인의 리소스 요청을 허용할 수 있다.

출처 (Origin)

이때 출처(Origin)는 도메인, 프로토콜, 포트 번호로 구성되는데, 출처가 다르다는 것은 이 세 가지 요소 중 하나라도 다르다는 의미이다.

규칙 정의

CorsRegistry 객체를 통해 경로와 규칙을 정의하게 된다.

addMapping: CORS 설정을 적용할 엔드포인트(api 경로)
allowedOrigins: CORS 요청을 허용할 오리진(도메인)
allowedMethods: 허용할 HTTP 메서드
allowedCredentials: 클라이언트가 서버로 요청할 때 쿠키(또는 인증 정보를 포함한 헤더)를 함께 보낼 수 있도록 허용할지 여부 (true로 설정할 경우 보안에 유의)

0개의 댓글