Programming

SpringBoot와 React 연동하기

seulye 2024. 9. 27. 16:55

Proxy 설정

CORS 관련 오류를 방지하기 위해 proxy를 설정해줘야 한다. 

 

src\main\frontend\setProxy.js

const { createProxyMiddleware } = require("http-proxy-middleware");

module.exports = function (app) {
  app.use(
    "/api",
    createProxyMiddleware({
      target: "http://localhost:8080",
      changeOrigin: true,
    })
  );
};

 

 

axios 설치 

npm i axios

 

 

src\main\frontend\src\App.tsx

import { useState, useEffect } from "react";
import reactLogo from "./assets/react.svg";
import viteLogo from "/vite.svg";
import "./App.css";
import axios from "axios";

function App() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    axios
      .get(`/sms/submit`)
      .then((response) => {
        console.log(response);
      })
      .catch((error) => {
        console.log(error);
      });
  });

  return (
    <>
      <div>
        <a href="https://vitejs.dev" target="_blank">
          <img src={viteLogo} className="logo" alt="Vite logo" />
        </a>
        <a href="https://react.dev" target="_blank">
          <img src={reactLogo} className="logo react" alt="React logo" />
        </a>
      </div>
      <h1>Vite + React</h1>
      <div className="card">
        <button onClick={() => setCount((count) => count + 1)}>
          count is {count}
        </button>
        <p>
          Edit <code>src/App.tsx</code> and save to test HMR
        </p>
      </div>
      <p className="read-the-docs">
        Click on the Vite and React logos to learn more
      </p>
    </>
  );
}

export default App;

 

Vite 초기 설정이 포함되어 있어서 소스가 길지만, 저 useEffect와 axios 부분만 추가해주었다. 

 

SpringBoot 설정

src\main\java\com\hansol\aes\config\WebMVCConfig.java

package com.hansol.aes.config;

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 WebMVCConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:3000")
                .allowedMethods("OPTIONS", "GET", "POST", "PUT", "DELETE");
    }
}

 

WebMVCConfig 파일을 하나 추가해주었다. 

 

 

src\main\java\com\{회사명}\aes\smsxml\controller\SMSController.java

package com.hansol.aes.smsxml.controller;

import com.hansol.aes.smsxml.service.SMSService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/sms")
public class SMSController {

    @Autowired
    private SMSService smsService;

    @GetMapping("/submit")
    public String submitRequest() {
        try {
            String output = smsService.execRequest();
            return output;
        } catch (Exception e) {
            return "SMS request failed: " + e.getMessage();
        }
    }
}

 

나는 백엔드 환경설정과 코딩을 먼저 해주었기 때문에 smsService 들어가명 더 로직이 있다!

암튼 이렇게 프론트와 백엔드 연동을 완료했다 ㅎㅎ

 

 

⚠️주의

http://127.0.0.1:3000/ 는 안 된다.

되게 하려면 

registry.addMapping("/**")
    .allowedOrigins("http://127.0.0.1:3000", "http://localhost:3000")
    .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS");

 

URL을 추가해줘야함!