프론트엔드와 백엔드 개발환경 연동하려고 합니다.
JavaSpringApplication/src/main 경로에서
create-react-app frontend
실행하여 스프링 부트 생성 후, React 기본 틀을 만들어 줍니다.
앞서 프론트엔드(Create React App)와 백엔드(Spring Boot)를 연동 확인을 하는 간단한 코드를 작성해봅니다.
이를 위해 접속한 기기의 IP주소를 확인하는 간단한 웹페이지를 만들어봅니다.
프론트엔드는 클라이언트의 IP주소를 알아내는 백엔드의 함수를 호출하고
그 함수에서 반환한 IP주소 값을 받아 화면에 표시하는 역할을 해야합니다.
먼저 백엔드와의 통신을 위해서 react에서 Axios 를 설치합니다.
npm i axios
설치가 완료된 후 package.json 파일을 확인해 보면 axios가 추가된 것을 알 수 있습니다.
프론트엔드에 개인설정을 합니다.
//src/configuration/web/WebConfig.ts
export class My {
ipAddress : string;
backEndPort : string;
constructor() {
this.ipAddress = "본인 장비 ip";
this.backEndPort = "백엔드로 통신할 포트 번호";
}
}
export default {My};
프론트엔드(Create React App)에 App.js 파일을 아래와 같이 수정합니다.
//src\App.js
import React, { useState, useEffect } from 'react';
import './App.css';
import customAxios from './customAxios';
function App() {
// IP주소 변수 선언
const [ip, setIp] = useState('');
// IP주소 값을 설정합니다.
function callback(data) {
setIp(data);
}
// 첫번째 렌더링을 다 마친 후 실행합니다.
useEffect(
() => {
// 클라이언트의 IP주소를 알아내는 백엔드의 함수를 호출합니다.
customAxios('/ip', callback);
}, []
);
return (
<div className="App">
<header className="App-header">
이 기기의 IP주소는 {ip}입니다.
</header>
</div>
);
}
export default App;
프론트엔드(Create React App)에 파일을 추가합니다.
//src\customAxios.js
import axios from 'axios';
import { My } from './configuration/web/WebConfig.ts';
let customAxios;
export default customAxios = function customAxios(url: string, callback: (data: any) => void) {
const my = new My();
axios({
url: '/test' + url,
method: 'post',
baseURL: `http://${my.ipAddress}:${my.backEndPort}`,
withCredentials: true,
}).then(function (response) {
callback(response.data);
});
};
백엔드는 함수를 실행하고 IP주소 값을 반환하는 역할을 해야합니다.
백엔드(Spring Boot)에 파일을 추가합니다.
//src\main\java\com\myapp\IPController.java
package com.myapp;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
public class TestController {
@PostMapping("/ip")
public ResponseEntity<String> ip (HttpServletRequest request) {
// 요청을 보낸 클라이언트의 IP주소를 반환합니다.
return ResponseEntity.ok(request.getRemoteAddr());
}
}
백엔드(Spring Boot)에 크로스 도메인 이슈를 해결하기 위해 web config 파일을 추가합니다.
//src\main\java\com\myapp\WebConfig.java
package com.myapp;
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 WebConfig implements WebMvcConfigurer {
String ipAddress;
String frontEndPort;
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/test/ip")
.allowCredentials(true)
.allowedOrigins("http://"+this.ipAddress+":"+this.frontEndPort);
}
}
프론트엔드에서는 Axios를 활용하여 백엔드와 통신하고,
백엔드에서는 클라이언트의 IP 주소를 반환하는 함수를 작성하였습니다.
또한, CORS(Cross-Origin Resource Sharing) 설정을 통해
크로스 도메인 이슈를 해결할 수 있었습니다.