개발/이슈

[Spring Boot + React] proxy 설정 이슈

bsorry 2024. 7. 22. 19:56

개요

Spring boot 와 react 프로젝트 연동 테스트에서 CORS 이슈 방지를 위해 proxy 설정을 했지만, proxy error가 발생했다.

 

Proxy error: Could not proxy request /api/test from localhost:3000 to http://localhost:8083/. See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED).

 

 

과정

간단하게 Spring Boot 프로젝트에 API 컨트롤러를 만들고, React 프로젝트 쪽에서 접근하도록 했다. 

 

    @RequestMapping(method = RequestMethod.GET, value = "/api/test")
    public ResponseEntity<Map<String, Object>> getApiTest() {
        
        Map<String, Object> respMap = new HashMap<String, Object>();
        respMap.put("data", "Spring Boot Response test");
        
        return new ResponseEntity<Map<String, Object>>(respMap, HttpStatus.OK);
    }

Spring Boot > ApiController.java

 

위와 같이 API 컨트롤러를 만들고

 

import logo from './logo.svg';
import './App.css';
import {useEffect, useState} from "react";

function App() {
  const [message, setMessage] = useState("");



  useEffect(() => {
      fetch("/api/test")
          .then((response) => response.json())
          .then((json) => setMessage(json.data));
  }, []);

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          {message}
        </p>
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

React > App.js

 

React 프로젝트의 App.js 내에 위와 같이 API에 접근하는 테스트 코드를 작성한다.

 

{
  "name": "react-test",
  "version": "0.1.0",
  "private": true,
  "proxy": "http://localhost:8083",
  
  .
  .
  .

React > package.json

 

단, CORS 이슈 방지를 위해 React 프로젝트의 설정 파일 package.json 에서 proxy 값을 Spring Boot의 주소로 설정해야한다. (위 방법 말고도 다른 방식으로 React 측에 설정하거나, Spring Boot 측에 설정하는 법도 있다.)

 

Proxy error: Could not proxy request /api/test from localhost:3000 to http://localhost:8083/. See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED).

 

이때 계속해서 위의 이슈가 발생하며, Spring Boot 서버에 접근을 하지 못하는 이슈가 발생했다.

 

해결

해결방법은 생각보다 굉장히 간단했는데, localhost 표기가 아닌 IPv4 표기로 127.0.0.1로 바꾸니 성공했다.

 

{
  "name": "react-test",
  "version": "0.1.0",
  "private": true,
  "proxy": "http://127.0.0.1:8083",
  
  .
  .
  .

React > package.json

 

 

React 실행화면에서 API를 호출하여 값을 표시하는 모습

 

관련하여 스택 오버플로우 링크를 첨부한다. 해당 내용을 참고하여 추측하면, 서버를 실행하는 컨테이너가 달라서 React 측에서 Spring Boot의 주소 localhost:8083을 호출해도 찾지못한 것 같다. 하지만 Django 및 Docker 환경이 아닌 단순한 Spring Boot, Tomcat 환경에서도 컨테이너에 영향을 받는지는 잘 모르겠다. 다른 이들의 예제 프로젝트를 보면 별 다른 설정 없이 localhost로 Spring Boot를 잘 호출하는 것 같은데, 관련하여 더 알게되는 것이 있으면 업데이트 하도록 해야겠다. 

 

https://stackoverflow.com/questions/50107816/react-proxy-error-could-not-proxy-request-api-from-localhost3000-to-http-l

 

React Proxy error: Could not proxy request /api/ from localhost:3000 to http://localhost:8000 (ECONNREFUSED)

I have a React frontend that uses jwt to authenticate with the Django backend. The backend works and is connecting just fine using django views, but when I try to proxy a request from React, it gi...

stackoverflow.com