일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- 이터레이터
- 리눅스
- 자바편
- 자료구조와함께배우는알고리즘입문
- 자료구조와 함께 배우는 알고리즘 입문
- 친절한SQL튜닝
- 목록처리
- resttemplate
- 코드로배우는스프링웹프로젝트
- 스프링부트핵심가이드
- Kernighan의 C언어 프로그래밍
- network configuration
- 선형대수
- 알파회계
- 데비안
- 코드로배우는스프링부트웹프로젝트
- 구멍가게코딩단
- 처음 만나는 AI 수학 with Python
- 네트워크 설정
- 서버설정
- 처음 만나는 AI수학 with Python
- /etc/network/interfaces
- 티스토리 쿠키 삭제
- 스프링 시큐리티
- GIT
- ㅒ
- baeldung
- iterator
- 페이징
- d
- Today
- Total
bright jazz music
리액트 앱과 백엔드 서버 연동 테스트 1 본문
실습을 위해 생활코딩의 영상을 참고하였다.
https://www.youtube.com/watch?v=VaAWIAxvj0A
1. 백엔드 서버 만들기
우선 백엔드 어플리케이션을 구동할 디렉토리에서 터미널을 열고 아래와 같은 순서로 명령한다.
hjcha@hjcha-AERO-15-Classic-SA:/usr/local/back-apps$ touch data.json
hjcha@hjcha-AERO-15-Classic-SA:/usr/local/back-apps$ vi data.json
hjcha@hjcha-AERO-15-Classic-SA:/usr/local/back-apps$ npx local-web-server
Need to install the following packages:
local-web-server@5.3.0
Ok to proceed? (y) y
Listening on http://hjcha-AERO-15-Classic-SA:8000, http://127.0.0.1:8000
브라우저에서 locahost:8000/data.json에 접근하였을 경우 위와 같이 표시된다.
2. 프론트 서버 만들기
$ npm create-react-app my-app
생성한 디렉토리 내부로 들어가서 아래의 명령어를 쳐준다.
$ npm run start
브라우저에서는 위와 같이 확인된다.
3. 백엔드 서버로 요청 보낼 수 있도록 수정하기
프론트 서버 디렉토리 내부의 /src/index.js 파일의 소스를 수정한다.
백엔드 서버로 요청을 보내기 위해서이다.
//index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
// <React.StrictMode>
// <App />
// </React.StrictMode>
<div>
<input type="button" value="get data" onClick={
function(){
fetch('http://localhost:8000/data.json')
.then(function(result){return result.json})
.then(function(json){console.log(json);})
}.bind(this)
}>
</input>
</div>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
기본 소스를 주석처리하고 아래에 <div>태그를 사용하여 새로운 소스를 추가하였다.
4. 버튼 눌러서 GET 요청 보내고 응답 확인하기
응답을 받았다.
그러나 응답을 받는 것은 $ npx local-web-server에서 사용한 local-web-server가 가진 기능 때문이다.
원래는 CORS(cross origin resource sharing) 문제로 응답을 받지 못해야 정상이다.
따라서 여기서는 정상적으로 응답을 받지 못했음을 가정하고 proxy를 사용하여 문제를 해결한다.
https://create-react-app.dev/docs/proxying-api-requests-in-development
Proxying API Requests in Development | Create React App
Note: this feature is available with react-scripts@0.2.3 and higher.
create-react-app.dev
5. package.json 파일에 proxy 항목 추가하기.
프론트 서버로 사용하는 디렉토리에 위치한 package.json을 수정해 준다.
중간에 아래의 내용을 추가해 주기만 하면 된다.
"proxy": "http://localhost:8000",
혹시 동작하지 않는다면 localhost 대신 "http://127.0.0.1:8000"을 사용해 볼 것.
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
//여기에 추가해 주었다.임의의 위치에 있어도 상관 없다.
"proxy":"http://localhost:8000",
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
수정한 뒤에는 프론트 서버를 재기동 해야 한다.
터미널에서 ctrl + c를 눌러 프로세스를 종료해 준다.
그리고는 $ 다시 npm run start 해준다.
6. 프론트서버디렉토리/src/index.js 파일 수정하기
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
// <React.StrictMode>
// <App />
// </React.StrictMode>
<div>
<input type="button" value="get data" onClick={
function(){
//fetch('http://localhost:8000/data.json')
fetch('/data.json')
.then(function(result){return result.json})
.then(function(json){console.log(json);})
}.bind(this)
}>
</input>
</div>
);
위에서는 주석처리해 주었다.
확실히 확인하기 위해 fetch('http://localhost:8000/data.json') 행을 지운 경우에도 잘 동작하였다.
다음 포스팅에서는 스프링 부트로 만든 백엔드 서버와 연동 테스트를 진행할 것이다.
'Framework > ReactJs' 카테고리의 다른 글
생활코딩: 리액트 프로그래밍 CRUD 기본 (0) | 2023.05.14 |
---|---|
리액트 앱과 백엔드 서버 연동 테스트4 (+ docker) (0) | 2023.04.09 |
리액트 앱과 백엔드 서버 연동 테스트3 (+ Nginx) (0) | 2023.04.09 |
리액트 앱과 백엔드 서버 연동 테스트 2 (0) | 2023.04.08 |
리액트 앱(ReactJs)와 엔진엑스(Nginx) 연동 (0) | 2023.04.06 |