보라코딩

Spring Boot 와 React.js 연동하기! 본문

코딩/Spring

Spring Boot 와 React.js 연동하기!

new 보라 2023. 8. 5. 17:20
개발환경
MySQL 8.0.34
Spring Boot 2.7.14
java 11.0.20
JPA
STS4 / VSC
Windows

 

 

 


 

 

 

File - new - other - Spring Starter Project

 

원하는 Name 입력하고 본인의 개발환경에 맞게 선택한다.

 

 

 

 

 

이렇게 만든 상태에서 바로 실행을 하면 

아래와 같은 에러를 볼 수 있다.

    ㄴ 원인 : JPA 의존성을 미리 추가해서

    ㄴ 해결방법 : pom.xml에서 jpa 부분 잠시 주석처리

 

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class


Action:

Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

 

 

 

 

web 패키지 만들고 MainController 클래스 생성

 

 

 

 

 

MainController
package com.boralog.blog.web;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MainController {

@GetMapping("/")
public ResponseEntity<?> findAll(){
return new ResponseEntity<String>("ok", HttpStatus.OK);
}

}

 

 

 

 

이렇게 입력하고 http://localhost:8080/ 실행하면

 

 

 

MySQL에 boralog 테이블 생성
create database boralog default character set utf8 collate utf8_general_ci;

show databases;

 

 

 

application.properties

server.port=8080

#한글깨짐 방지

server.servlet.encoding.force-response=true

 

#MySQL

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.datasource.url=jdbc:mysql://localhost:3306/boralog?serverTimezone=UTC

spring.datasource.username=root

spring.datasource.password=비밀번호!!!!!

 

#스키마 생성

spring.jpa.hibernate.ddl-auto=create

#DDL 생성 시 데이터베이스의 고유기능을 사용하는가?

spring.jpa.generate-ddl=false

#실행되는 SQL문을 보여줄 것인가?

spring.jpa.show-sql=true

#데이터베이스는 무엇을 사용하는가?

spring.jpa.database=mysql

#로그레벨

logging.level.org.hibernate=info

#Mysql 상세지정

spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect

 

 


 

 

npm create-react-app 시 자꾸 오류가 나서 yarn으로 했다.

 

yarn create react-app boralog
npm install -g yarn
npm install -g yarn

 

 

 

 

Axios를 이용한 서버 통신
(fetch도 가능)

 

 

 

Axios : 백엔드와 프론트엔드 사이의 통신을 쉽게 하기 위해 사용하는 라이브러리

 

프론트엔드

 

axios 설치하기

npm install axios --save

 

 

src/App.js에 내용 입력하기

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

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

    useEffect(() => {
           axios.get("http://localhost:8080/bora")
           .then(response => setHello(response.data))
           .catch(error => console.log(error))



          //fetch로 하고 싶다면 아래처럼~
          // fetch('http://localhost:8080/bora')
          // .then(response => response.text())    <-- string이면 text()이고 map이나 list면 json()
          // .then(message => {
          //  setHello(message);
          // });

    }, []);

  return (
    <div>
    백엔드에서 가져온 데이터입니다 : {hello}
    </div>
  );
}

export default App;

 

 

yarn start 실행

 

 

 

 

 

백엔드

Controller.java 생성 후 내용 입력

(CORS 관련 오류 방지)

package com.boralog.blog.web;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin(originPatterns="http://localhost:3000")
//@CrossOrigin("*")
public class MainController {


@GetMapping("/bora") public ResponseEntity<?> findAll(){ return new
ResponseEntity<String>("ok", HttpStatus.OK); }


// @GetMapping("/bora")
// public List test() {
// List<String> list = new ArrayList<>();
// list.add("list로 해도 되구요~");
// return list;
// }

// @GetMapping("/bora")
// public String test() {
// return "String으로 해도 됩니다~~";
// }


}

 

 


 

 

 

프론트엔드로 백엔드 데이터 가져오기 성공!

 

 

 

 

 

 


 

 

DB 데이터도 연동하고 싶다면~~

 

 

 

Controller

우선 PostMapping으로 데이터 넣고

GetMapping으로 확인하기

 

package com.boralog.blog.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import com.boralog.blog.domain.BlogEntity;
import com.boralog.blog.domain.MainRepository;
import com.boralog.blog.service.MainService;

@RestController
@CrossOrigin("*")
public class MainController {


@Autowired
private MainRepository mainRepository;


@GetMapping("/main")
public List<BlogEntity> findAll(){
return mainRepository.findAll();
}


@PostMapping("/main")
public BlogEntity insert() {
final BlogEntity blog = BlogEntity.builder()
.writer("글쓴이야")
.content("블로그 화이팅")
.build();
return mainRepository.save(blog);
}

}

 

 

 

 

App.js

useState와 map을 이용하여 보여주기!

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

 

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

    useEffect(() => {
           axios.get("http://localhost:8080/main")
           .then(response => setData(response.data))
           .catch(error => console.log(error))
 
    }, []);

 

  return (
    <div>
        {data.map(item => (
        <div key={item.id}>
          <p>ID: {item.id}</p>
          <p>Writer: {item.writer}</p>
          <p>Content: {item.content}</p>
        </div>
      ))}
    </div>
  );
}

 

export default App;
 

 

 

 

 

 

 

 

 

 

 

 

 


 

Cors 관련

 

 

매번 controller에 입력하기 귀찮으므로 Application.java에서 설정하면 편리하다  ~

 

@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOriginPatterns();
}
};
}

 

 

 

 

 

 

 

 

 

 

 

 

 


 

 

그밖에 참고..

 

 

 

dbdiagram

erd 대체로 사용하기 좋다

 

 

dbdiagram.io - Database Relationship Diagrams Design Tool

 

dbdiagram.io

 

 

참고했던 내용
 

Spring Boot + React.js 개발환경 연동하기

Spring Boot와 React.js를 연동해 개발환경을 만들고, 빌드해서 jar 파일로까지 만들어보는 과정입니다.

velog.io