Frontend : React , Backend : Spring boot

Overview

React(Front) + Spring Boot(Back)

작업 하기 앞서, React와 Spring Boot는 각각 다른 서버에서 돌아가기 때문에, 연동시 Front에 문제가 생기면 Back까지 문제가 생길 수 있다.

하지만, Spring Boot에서 React와 같은 view를 제공하기로 했다.


1. react + spring boot 환경 구성 및 연동


먼저 연동하기 위한 환경을 구성하기 위해 react를 설치해야 한다.
$ npx create-react-app frontend 명령어를 통해 react 를 설치할 수 있는데, 이 파일은 spring -boot 프로젝트 안에 넣어줘야 한다.

명령어를 실행하기 위해 npm을 설치해야 한다. npx는 npm의 추가 도구이다. (5.2.0버젼부터 추가 도구를 제공한다.)


npm을 설치하기 위해서는 Node.js를 설치해야한다.

Node.js 는 구글링을 통해 쉽게 설치할 수 있다.


react를 설치하게 되면, 리액트와 스프링부트가 다른 포트에서 실행되기 때문에 CORS문제가 발생하는데, 이를 위해서 react의 proxy를 잡아줘야한다.

[Package.json]
프록시란? 서버와 클라이언트 사이에 중계기로서 대리로 통신을 수행하는 것을 가리킨다.

{
  "name": "fronted",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.1",
    "@testing-library/react": "^12.1.2",
    "@testing-library/user-event": "^13.5.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "5.0.0",
    "web-vitals": "^2.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

  "proxy":"http://localhost:8080",

  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

프록시를 잡은 이후에 예제를 이용해 Rest.Api를 구현해보았다.

[App.js]

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

function App () {
const [message, setMessage] = useState("");
useEffect(() => {
fetch('/api/hello')
.then(response => response.text())
.then(message => {
setMessage(message);
});
},[])
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo"/>
<h1 className="App-title">{message}</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
)
}
export default App;

다음과 같이 변경해주면 둘 다 서버를 켰을 때, react에 spring boot가 적용됨을 볼 수 있다.따로 서버를 켜주는 일은 불편하니 스프링부트가 maven을 통해 빌드 될 때, npm이 실행되게 함으로서 연동할 수 있다.

[pom.xml]
이때, plugin은 최신 버젼, npm과 node.js는 자신의 로컬 버젼과 같아야 한다.
https://github.com/eirslett/frontend-maven-plugin 최신 버젼은 다음을 참고하자.

<plugin>
				<groupId>com.github.eirslett</groupId>
				<artifactId>frontend-maven-plugin</artifactId>
				<version>1.12.1</version>
				<configuration>
				<workingDirectory>frontend</workingDirectory>
				<installDirectory>target</installDirectory>
				</configuration>
				<executions>
				<execution>
				<id>install node and npm</id>
				<goals>
				<goal>install-node-and-npm</goal>
				</goals>
				<configuration>
				<nodeVersion>v16.13.1</nodeVersion>
				<npmVersion>8.1.2</npmVersion>
				</configuration>
				</execution>
				<execution>
				<id>npm install</id>
				<goals>
				<goal>npm</goal>
				</goals>
				<configuration>
				<arguments>install</arguments>
				</configuration>
				</execution>
				<execution>
				<id>npm run build</id>
				<goals>
				<goal>npm</goal>
				</goals>
				<configuration>
				<arguments>run build</arguments>
				</configuration>
				</execution>
				</executions>
			</plugin>

이후 ./mvnw clean install 을 통해 재빌드를 하면 spring boot 서버를 키는 것만으로 maven에서 react와 spring boot를 같이 패키징을 해 실행 할 수 있다.


추가로 plugin을 다음과 같이 추가한다면, react에 있는 build 폴더를 spring boot project에 포함시킬 수 있고, frontend 와 backend 나눠서 작업이 가능해진다.

[pom.xml]

<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<phase>generate-resources</phase>
<configuration>
<target>
<copy todir="${project.build.directory}/classes/public">
<fileset dir="${project.basedir}/frontend/build"/>
</copy>
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
You might also like...

Java GUI Frontend for XCH Forks

Java GUI Frontend for XCH Forks

ForkFarmer Java GUI Frontend for XCH Forks. Discord: https://discord.gg/Mx9ZNHta Requires JRE 1.8 or greater to run: https://www.java.com/en/download/

Nov 8, 2022

Angular Final Assignment - Keep Note frontend

Angular Final Assignment - Keep Note frontend Objective The Objective of this level of Keep is to cover the following areas : Components Design Compon

Jan 29, 2022

This is the RestFul API using SpringBoot made to integrate the frontend of this repository.

This is the RestFul API using SpringBoot made to integrate the frontend of this repository. Requirements For building and running the application you

Jan 21, 2022

about learning Spring Boot via examples. Spring Boot 教程、技术栈示例代码,快速简单上手教程。

about learning Spring Boot via examples. Spring Boot 教程、技术栈示例代码,快速简单上手教程。

Spring Boot 学习示例 Spring Boot 使用的各种示例,以最简单、最实用为标准,此开源项目中的每个示例都以最小依赖,最简单为标准,帮助初学者快速掌握 Spring Boot 各组件的使用。 Spring Boot 中文索引 | Spring Cloud学习示例代码 | Spring

Jan 1, 2023

spring boot 实践学习案例,是 spring boot 初学者及核心技术巩固的最佳实践。另外写博客,用 OpenWrite。

spring boot 实践学习案例,是 spring boot 初学者及核心技术巩固的最佳实践。另外写博客,用 OpenWrite。

推荐工具: 微信公众号 Markdown 编辑器 - OpenWrite:Markdown 微信编辑器是一款专业强大的微信公众平台在线编辑排版工具,提供手机预览功能,让用户在微信图文 、文章、内容排版、文本编辑、素材编辑上更加方便。 - 更多介绍 博客群发平台 一、支持泥瓦匠 Spring Boot

Jan 5, 2023

Spring-Boot-Plus is a easy-to-use, high-speed, high-efficient,feature-rich, open source spring boot scaffolding

Spring-Boot-Plus is a easy-to-use, high-speed, high-efficient,feature-rich, open source spring boot scaffolding

Everyone can develop projects independently, quickly and efficiently! What is spring-boot-plus? A easy-to-use, high-speed, high-efficient, feature-ric

Dec 31, 2022

Two Spring-boot applications registering themselves to an spring-boot-admin-server application as separate clients for the purpose of monitoring and managing the clients

Two Spring-boot applications registering themselves to an spring-boot-admin-server application as separate clients for the purpose of monitoring and managing the clients

Spring-boot-admin implementation with 1 Server and 2 clients Creating a Server application to monitor and manage Spring boot applications (clients) un

Dec 6, 2022

The Spring Boot Sample App on K8S has been implemented using GKE K8S Cluster, Spring Boot, Maven, and Docker.

gke-springboot-sampleapp 👋 The Spring Boot Sample App on K8S has been implemented using GKE K8S Cluster, Spring Boot, Maven, and Docker. Usage To be

Feb 1, 2022

Spring Boot Migrator (SBM) - a tool for automated code migrations to upgrade or migrate to Spring Boot

Spring Boot Migrator (SBM) - a tool for automated code migrations to upgrade or migrate to Spring Boot

Spring Boot Migrator uses and is compatible to OpenRewrite, a powerful mass refactoring ecosystem for Java and other source code.

Jan 2, 2023
Owner
심재철
심재철
该仓库中主要是 Spring Boot 的入门学习教程以及一些常用的 Spring Boot 实战项目教程,包括 Spring Boot 使用的各种示例代码,同时也包括一些实战项目的项目源码和效果展示,实战项目包括基本的 web 开发以及目前大家普遍使用的线上博客项目/企业大型商城系统/前后端分离实践项目等,摆脱各种 hello world 入门案例的束缚,真正的掌握 Spring Boot 开发。

Spring Boot Projects 该仓库中主要是 Spring Boot 的入门学习教程以及一些常用的 Spring Boot 实战项目教程,包括 Spring Boot 使用的各种示例代码,同时也包括一些实战项目的项目源码和效果展示,实战项目包括基本的 web 开发以及目前大家普遍使用的前

十三 4.5k Dec 30, 2022
循序渐进,学习Spring Boot、Spring Boot & Shiro、Spring Batch、Spring Cloud、Spring Cloud Alibaba、Spring Security & Spring Security OAuth2,博客Spring系列源码:https://mrbird.cc

Spring 系列教程 该仓库为个人博客https://mrbird.cc中Spring系列源码,包含Spring Boot、Spring Boot & Shiro、Spring Cloud,Spring Boot & Spring Security & Spring Security OAuth2

mrbird 24.8k Jan 6, 2023
Application for creating blog posts, developed with Java using Spring Framework for backend and Angular along with PrimeNG Library for frontend development.

Application for creating blog posts, developed with Java using Spring Framework for backend and Angular along with PrimeNG Library for frontend development.

Áureo Carmelino 10 Nov 27, 2022
There are two challenges one is to create a backend api the other is to create a frontend application to consume the public data api devall.

Sobre | Desafio | Resolução | Tecnologias | Execução | Itexto desafio tecnico Sobre os Desafios existem dois desafios um é criar uma api backend o out

fabricio S Miranda 1 Oct 18, 2021
Projeto criado no Santander Dev Week 2022 + DIO com o intuito de desenvolver uma camada de APIs (backend) que será utilizada pelo frontend.

Santader Dev Week + DIO 2022 - APIs Backend da aplicação de movimentação financeira Este repositório contém o backend da aplicação que foi desenvolvid

Pedro Antunes Negrão 2 Sep 7, 2022
Projeto criado na semana Spring React organizado pela escola Dev Superior com foco na prática/aprendizado das tecnologias Spring e React.

DSVendas Projeto criado na semana Spring React organizado pela escola Dev Superior com foco na prática/aprendizado das tecnologias Spring e React. htt

João Gabriel 3 May 18, 2021
Spring Boot microservices app with Spring Cloud, Robust and resilient backend managing e-Commerce app

e-Commerce-boot μServices Important Note: This project's new milestone is to move The whole system to work on Kubernetes, so stay tuned. Introduction

Selim Horri 65 Dec 23, 2022
Spring for GraphQL demo project with a Vue frontend.

Spring Books - Hello GraphQL This is a demo project that will introduce you to [https://spring.io/projects/spring-graphql](Spring for GraphQL). The Sp

Dan Vega 11 Dec 2, 2022
Spring Boot Login and Registration example with MySQL, JWT, Rest Api - Spring Boot Spring Security Login example

Spring Boot Login example with Spring Security, MySQL and JWT Appropriate Flow for User Login and Registration with JWT Spring Boot Rest Api Architect

null 58 Jan 5, 2023
Spring boot backend for marble guessing game inspired by Squid Game TV series.

Back-end for marble guessing game inspired by Squid Game TV series. Built with Spring-boot and WebSocket.

Zaid 4 Sep 3, 2022