React와 Node.js 연동

윤태현·2023년 7월 9일
1

REACT

목록 보기
11/19
post-thumbnail

순서

  1. 프로젝트 폴더 생성 후 frontend 폴더 / backend 폴더 생성
  2. frontend 폴더에 React 설치
  3. proxy 설정
  4. nodemon 설치

1. 프로젝트 폴더 생성

mkdir frontend
mkdir backend

2. React 설치 / server.js 생성 후 라이브러리 설치

// frontend 폴더

cd frontend
npx create-react-app .
npm install http-proxy-middleware
// backend 폴더

cd backend
npm init -y
npm install express
npm install cors
// 클라이언트

const userId = 'user';
const password = '1234';

fetch('/api/userData', {
    method: 'POST',
    body: JSON.stringify({userId: userId, password: password}),
    credentials: 'include',
    headers: {
        'Content-Type': 'application/json'
    },
})
.then(res => res.json()).then(data => console.log(data))
.catch(err => console.log(err));
// server.js

const express = require('express');
const cors = require("cors");

const app = express();
app.use(express.json());
app.use(cors({
    origin: 'http://localhost:3000',
    credentials: true,
}));

app.post('/api/userData', (req, res) => {
    console.log(req.body);
    res.json('Data received');  // json 형태로 응답을 보냄
});

app.listen(3001, () => {		// 3001번 포트로 서버 실행
    console.log("서버 실행")
});

3. proxy 설정

proxy

  • 컴퓨터 네트워크에서 서버와 클라이언트 사이에서 요청과 응답을 중계하는 서버를 의미

  • 다른 서버로의 자원 요청 중계를 통해 분산 시스템 구조를 단순화할 수 있음

  • 클라이언트로부터 요청된 자원들이 캐시로 임시 저장되어 있어 자원을 재요청할 경우 프록시 서버에 있는 데이터를 제공 받아 데이터 전송시간과 서버의 외부 트래픽을 감소 시킴

  • 서버를 대상으로 하는 외부 공격이 들어올 경우 필터링하여 클라이언트 측의 보안을 향상 시킬 수 있음

  • proxy 설정은 2가지 방법이 있다.
    • package.json proxy 설정하기
    • setupProxy.js 파일을 이용한 http-proxy-middleware 라이브러리 사용하기

3-1 package.json proxy 설정

  • 설정이 간단하며 대부분의 단순한 proxy 필요 사항을 충족시키므로 특별히 복잡한 프록시 설정이 필요하지 않는 경우에 유용함

  • 여러 개의 서로 다른 엔드포인트에 대한 프록시 설정이 필요한 경우나, 다양한 HTTP 메소드를 가진 다양한 경로를 가진 프록시 설정이 필요한 경우에는 부족함

{
  "name": "frontend",
  "version": "0.1.0",
  "proxy": "http://localhost:3001",		// server의 포트 번호가 3001일 경우
  // ...other configurations
}
  • 클라이언트에서 요청 시에는 '/api/주소' 이런 식으로 URL 호출을 해야 함

3-2 setupProxy.js 파일 설정

  • 다양한 엔드포인트와 HTTP 메소드에 대해 다양한 프록시 설정이 가능

  • 사용자 정의 함수를 통해 프록시 요청을 변경하거나 커스터마이즈하는 등의 추가적인 기능을 제공

  • 별도의 import 필요 없음

  • frontend/src 폴더 안에 setupProxy.js 파일 생성 (폴더명은 무조건 저렇게 작성해야 함)

// setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  	app.use(
    	'/api',									// '/api'로 시작하는 모든 요청은 이 미들웨어를 거침
    	createProxyMiddleware({
      		target: 'http://localhost:3001',	// 서버의 포트를 작성
      		changeOrigin: true,					// 요청 헤더의 호스트 헤더를 대상 서버의 URL로 변경 
    	})
  	);
}
  • 클라이언트에서 fetch를 사용하여 '/api'로 시작하는 경로로 요청을 보내면 'http://localhost:3001' 서버로 프록시되게 됨

4. nodemon 설치

  • 파일이 변경될 때마다 애플리케이션을 자동으로 재시작해주는 역할을 함
  • Node.js는 코드 변경 시 서버를 재시작해야 하는 불편함이 있어 Nodemon을 사용
npm install -g nodemon
// package.json 수정
{
  "name": "backend",
  "version": "1.0.0",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node ./server.js",
    "dev": "nodemon ./server.js"
  },
  // ...other configurations
}

서버 실행

npm run dev

0개의 댓글