Spring Boot, React 연동하기

hwang·2024년 11월 27일

1. React프로젝트 package.json에 proxy 추가(나는 spring boot 서버 포트를 9090으로 설정했음)

2. Spring Boot 테스트용 API 만들기

@RestController
@RequestMapping("/api")
public class HelloController {
    @GetMapping("/hello")
    public String sayHello() {
        return "Hello from Spring Boot!";
    }
}
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("http://localhost:3000");
    }
}

3. React에서 Spring Boot API 호출

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

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

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

    return (
        <div>
            <h1>{message}</h1>
        </div>
    );
}

export default App;

4. Spring Boot 실행(Applicaiotn 클래스 실행), React 개발서버 실행(npm start)

브라우저에서 http://localhost:3000으로 접속하여 확인

profile
🍀

0개의 댓글