IT'S DO
article thumbnail
Published 2024. 10. 30. 14:10
[springboot + react] 연동 개발/React
728x90

springboot 터미널 창에서

 

# springboot + react 연동

 

1. react install

cd src/main

 

해당 위치에서

npx create-react-app react(원하는 이름)

약 1~2분 기다리면 src/main 아래에 react라는 폴더 만들어짐.

 

2. react start

cd react

npm start

 

인터넷 브라우저에서 

주소 : localhost:3000

 

3. springboot와 react 간에 proxy 열기

 

하는 이유 : 안하면 콘솔창에 CORS 관련 에러 나옴.

 

package.json 파일 안에서

proxy : "http://localhost:8080" 

application.yml에서 port 변경시 그 port로 적어주기

 

4. axios 설치

터미널 react 폴더 위치에서 

npm install axios --save

백엔드와 클라이언트 단에서 통신을 하기 위해 사용하는 라이브러리

 

5. App.js에 내용 적기

import React, {useEffect, useState} from 'react';
import axios from 'axios';

function App() {
   const [hello, setData] = useState('')

    useEffect(() => {
        axios.get('/api/data')
        .then(response => setData(response.data))
        .catch(error => console.log(error))
    }, []);

    return (
        <div>
            Backend data : {hello}
        </div>
    );
}

export default App;

 

6. java.controller 

package com.cobim.cobimproj.controller.react.controller;

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

@RestController
public class HelloWorldController {

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

 

7. springboot, react 실행

springboot는 개발툴 마다 실행 방법 다름 실행.

react는 npm start

브라우저 

 

# localhost:8080/api/data

 

# localhost:3000

(springboot + react 연동)

 

profile

IT'S DO

@멋진놈

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!