관리 메뉴

SIMPLE & UNIQUE

1-2강 : react, node 개발환경 세팅, 프록시 설정 본문

탈잉 강의 자료/2021_비전공자도 가능한 웹 프로젝트

1-2강 : react, node 개발환경 세팅, 프록시 설정

착한코딩 2021. 3. 27. 18:18

1-2강_11번까지 소스.zip
0.03MB
1-2강_완료코드.zip
0.03MB

1_2 목표 : create-react-app으로 react 서버를, express로 node 서버를 각각 구동한다. proxy를 설정한다. 
react페이지에서 get/post 방식으로 api를 호출해, node 서버의 json 데이터를 가져온다.

 

1. node.js 설치

nodejs 공식 사이트에서 최신버전이 아닌 이전 버전(14.4.0)을 설치한다. (검증된 버전)

 

아래 링크에서 윈도우(64비트)는 node-v14.4.0-x64.msi 파일을

                   Mac은 node-v14.4.0.pkg 파일을 다운로드 한다.

 

https://nodejs.org/download/release/v14.4.0/

 

설치확인 : 윈도우는 cmd > node -v로 버전 확인    ( win + r > cmd 실행)

              Mac은 터미널에서 node -v로 버전 확인 ( cmd + space > Spotlight > terminal.app 실행)

2. VS code 설치

https://code.visualstudio.com/

 

3. cmd 또는 터미널을 띄운다

 

4. workspace로 사용할 폴더에 접근한다. 

cd C:\react200

5. create-react-app 글로벌 설치 후, 프로젝트를 생성한다.

npm : Node Package Mananger의 약어로 개발에 필요한 노드모듈=패키지들을 제공.

        쉽게 다운받아 사용 가능하게 해준다.

yarn : npm 대체제. 페이스북에서 만든 패키지. npm에 비해 가볍고 빠르다. 따로 설치필요.

//글로벌 설치
npm install -g create-react-app

//프로젝트 생성
create-react-app client

이후부터, client폴더가 생성된 C:\react200\client경로를 리액트 경로라고 부른다.

react 경로 C:\react200\client에서 npm start로 react 서버 구동을 확인한다.

creact-react-app은 브라우저에서 url(http://localhost:3000/)을 호출하지 않아도,

자동으로 브라우저를 오픈해 페이지를 보여준다. 브라우저는 크롬(chrome)을 권장한다.

 

 

6. node express 프레임워크 설치

이후부터, 처음에 생성한 react200폴더 경로(C:\react200)를에서 노드경로라고 한다.

express 프레임워크를 생성하기 위해, express-generator를 설치한다.

설치 완료후, express명령어로 project2021이라는 node 프로젝트 폴더를 생성한다.
cmd창을 하나 더 열어도 되고, 기존 react서버가 구동되고 있는 cmd창에서 [ctrl]+c를 여러번 누르면 서버를 종료시킬 수 있다.(다시 명령어를 실행할 수 있는 상태가 된다)

// 글로벌 설치
npm i -g express-generator 
// 프로젝트 생성
express project2021

웹개발을 할 때, 보통 프레임워크(framework)라는 것을 사용한다. 프레임워크는 웹개발에 필요한 필수적인 요소들을 반증 완성된 코드로 제공한다. 좀 더 편하고 효율적으로 개발할 수 있게 도와주는 소스틀이다. 

react에서는 creact-react-app를, node에서는 express라는 프레임워크를 사용해 간편하게 기본 서버를 세팅할 수 있다.

(creact-react-app은 보통 템플릿이라고 하는데, 용어차이일뿐 프레임워크라고 봐도 된다.)

 

생성된 node 프로젝트 폴더 project2021는 사용하지 않을 것이다. 이 폴더 안에있는 파일&폴더들을 상위 경로(node경로)인 C:\react200으로 옮기고 project2021폴더는 삭제한다.

 

폴더 변경 전

폴더 변경 후

react와 node 서버 모두 기본 포트가 3000으로 설정되어 있다.

포트 중복을 피하기 위해, bin/www 파일에서 node 서버의 포트를 5000으로 바꿔준다.

node 경로 > app.js 파일도 react에 동일한 이름의 파일이 있기 때문에 server.js로 파일명을 바꿔준다.

//node 경로 > bin/www 파일
var port = normalizePort(process.env.PORT || '3000');//수정전
var port = normalizePort(process.env.PORT || '5000');//수정후

var app = require('../app');//수정전
var app = require('../server');//수정후

node 경로 C:\react200 에서 npm install로 패키지를 설치해주고

npm start로 node서버 구동을 확인한다. 브라우저에서 localhost:5000 또는 127.0.0.1:5000을 호출해, node 서버 구동을 확인한다.

 

 

7. 프록시 추가

react 경로 C:\react200\client 에서 package.json파일에 프록시를 추가해준다. 

프록시는 react에서 node API를 호출할 때, 호출 url을 간편하게 사용할 수 있게 한다.

예시) node api주소가 localhost:5000/users라면, 프록시 사용으로 /users경로만 호출할 수 있다.

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "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"
    ]
  },
  "proxy" : "http://127.0.0.1:5000"
}

패키지 : 프로젝트에 필요한 프로그램들을 npm install [프로그램명]으로 설치하게 되는데, 이 프로그램을 패키지라고 부른다.

node_modules폴더 : 패키지를 설치하면 실제 프로그램들이 설치되는 경로. 여기 저장되는 폴더와 파일들을 용량이 크고, 개수도 많기 때문에 프로젝트 소스 이동시에 제외한다.

package.json파일 : 설치 패키지마다 고유 버전이있는데, 설치시점의 버전을 기록해두는 소스이다. 이 파일 덕분에 소스 이동 or 서버배포시 node_modules 폴더안의 모듈파일들을 옮기지 않아도 된다. 소스 경로에서 npm install 명령어를 실행하면 package.json에 기록된 패키지들을 한번에 설치해 준다.

 

8. node 경로는 back-end 서버 역할만 할 것이기 때문에, public과 views폴더는 삭제해준다.

9. react > view 경로 생성

  react 경로 C:\react200\client\src에 components 폴더를 생성한다.

react에서는 디폴트 root경로가 src폴더인데, /components가 추가됐으니 코드 수정이 필요하다.

/client/src/index.js 파일을 아래와 같이 수정한다. 기존의 내용과 수정된 것은 /components경로가 추가되고, 수정된 경로의 App.js파일을 BrowserRouter로 사용하겠다는 내용이다. 

//client/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import { BrowserRouter } from 'react-router-dom';
import App from './components/App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render((
    <BrowserRouter>
        <App />
    </BrowserRouter>
), document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();


App.js 파일은 client/src/components 경로로 옮기고, 아래와 같이 수정한다. App.css 파일은 삭제한다.

route(라우트) : 라우팅이란 호출 경로에 따라, 사용할 소스를 연결해주는 것을 말한다. react에서는 view를 나타내는 단위인 component파일을 연결하고, node에서는 백엔드 로직을 구현한 router파일을 연결한다.

/Api_test 경로로 유입된 호출 Api_test.js 파일로 이동시킨다는 내용이다.

//client/src/components/App.js
import React, { Component } from 'react';
import { Router, Route, Switch } from "react-router";

import Api_test from './Api_test'

class App extends Component {
  constructor (props) {
    super(props);
    
    this.state = {
    }
}
  componentDidMount() {}
  render () {
    return (
      <div className="App">
          <Switch>
            <Route exact path='/' component={Api_test} /> // root 경로일 경우 라우팅
            <Route path='/Api_test' component={Api_test} />
          </Switch>
      </div>
    );
  }
}

export default App;

페이지 라우팅을 위해 C:\react200\client 경로에서

react_router_dom과 react-router를 설치한다.

npm install --save react-router-dom
npm install --save react-router

client 경로에 아래 명령어를 실행한다. --save을 써주면 package.json에 기록하면서 설치한다.

 

10. http통신(get, post방식)으로 node Api 호출

 

server.js를 보면 기본적으로 indexRouter와 usersRouter 세팅이 되어있다.

react에서 node api를 호출해 proxy가 정상적으로 동작하는지 확인하기 위해서, 이미 세팅되어 있는 usersRouter를 사용하려고 한다.

 

server.js의 불필요한 소스를 삭제하고 아래와 같이 수정한다.

var express = require('express');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

app.use('/', indexRouter);
app.use('/users', usersRouter);

module.exports = app;

/routes/users.js 파일을 아래와 같이 수정한다.

res.send에서 텍스트 대신 json형태의 데이터를 반환한다. post 호출을 위해 post router를 추가했다.

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  console.log('user router get')
  res.send({'message':'node get success'});
});

/* Post users listing. */
router.post('/', function(req, res, next) {
  console.log('user router post')
  res.send({'message':'node post success'});
});

module.exports = router;

post 비동기 호출을 위해 C:\react200\client 경로에서

axios을 설치한다.

npm install --save axios

/src/components/폴더에 Api_test.js파일을 추가하고 아래 소스를 작성한다.

import React, { Component } from 'react';
const axios = require('axios');

class App extends Component {
  state = {
    response: '',
  };
  
//페이지 로드시 실행 GET TEST
componentDidMount() {
  this.callApi()
    .then(res => this.setState({ response: res.express }))
    .catch(err => console.log(err));
}

callApi = async () => {
  try {
    const response = await fetch('/users');
    const body = await response.json();
    alert(body.message)
    if (response.status !== 200) throw Error(body.message);
    return body;
  } catch (error) {
    alert(error)
  }
};

// post 호출하기 버튼 클릭시 node api post 호출
submitClick = async e => {
  axios.post('/users', {
  })
  .then( response => {
      alert(response.data.message)
  })  

}

render() {
    return (
        <div>
          <button className="s_bt" type="submit" onClick={this.submitClick}>post 호출</button>
        </div>
    );
  }
}

export default App;

 

11. cmd 창을 2개 열고 react, node 서버를 각각 실행한다.

cd 명령어로 node 경로 들어가 npm start 명령어로 node 서버를 실행한다.

  cd C:\react200
  npm start

cd 명령어로 react 경로 들어가 npm start 명령어로 react 서버를 실행한다.

cd C:\react200\client
npm start

react 서버에서 아래와 같이 alert이 뜬다면 정상적으로 react 에서 node get api를 호출한 것이다.

[post 호출] 버튼을 클릭했을때,  아래와 같이 alert이 뜬다면 정상적으로 react 에서 node post api를 호출한 것이다.

12. 하나의 cmd, 하나의 명령어로 react node 서버를 동시 구동한다.

  11번에서 cmd창 2개를 열고, node서버와 react서버를 각각 구동시켰다. concurrently라는 패키지를 사용하면, 여러개의 명령어를 하나의 명령어에 연결해 사용할 수 있다. 이 명령어는 yarn을 통해 실행하도록한다.

yarn과 concurrently를 아래 명령어로 설치한다.

// window인경우
npm install -g yarn
// mac 에서 homebrew 사용할 경우
brew install yarn
npm install concurrently --save

 

concurrently를 사용하면 여러개의 명령어를 하나의 콘솔에서 동시에 실행할 수 있다.

npm 설치시  --save 옵션을 추가하면 package.json파일 > "dependencies":{} 안에 패키지명과 버전이 추가된다.

 

node 경로(C:\react200)에 있는 package.json파일을 아래와 같이 수정한다

 

코드설명 : concurrently를 사용하면 yarn server 라를 명령어와 yarn client라는 명령어를 동시에 실행 할 수있다.

yarn dev 명령어는 "concurrently --kill-others-on-fail \"yarn server\" \"yarn client\"" 를 실행시킨다.

yarn server는 nodemon server.js 라는 명령어를 실행해 node 서버를 키고,

yarn client는 cd client로 react 경로에 들어가 yarn start 명령어로 react 서버를 실행시킨다.

 

이렇게 하면 yarn dev라는 하나의 명령어로 react와 node 서버를 모두 켤 수 있다.

{
  "name": "project2021",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "client": "cd client && yarn start",
    "server": "nodemon server.js",
    "dev": "concurrently --kill-others-on-fail \"yarn server\" \"yarn client\""
  },
  "dependencies": {
    "concurrently": "^5.0.2",
    "cookie-parser": "~1.4.4",
    "debug": "~2.6.9",
    "express": "~4.16.1",
    "http-errors": "~1.6.3",
    "jade": "~1.11.0",
    "morgan": "~1.9.1"
  }
}

nodemon명령어를 사용하기 위해, 아래 명령어를 실행한다. nodemon으로 node서버를 구동하면, 소스를 수정했을 때 자동 빌드를 해준다. 즉, 소스수정후 서버재시작을 하지 않고, 새로고침만 하면 반영된다. (xml파일은 제외)

npm install -g nodemon

nodemon : 소스코드가 바뀔 때마다 자동으로 노드를 재실행주는 패키지

 

바뀐 코드(nodemon server.js)에서는 www 파일이 아닌 server.js 파일을 실행하니,

server.js에 5000번 포트설정 코드를 추가해 줘야한다.

var express = require('express');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

app.use('/', indexRouter);
app.use('/users', usersRouter);

const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Listening on port ${port}`));

node경로(C:\react200)에서 yarn dev 명령어를 실행하면, 아래와 같이 하나의 명령어로 react, node 서버를 동시에 구동할 수 있다.

https://taling.me/Talent/Detail/19341

 

[비전공자도 가능한 웹 프로젝트] REACTJS NODEJS MYSQL AWS 웹개발 | 탈잉

✔ 수업 목표 & 5주 뒤 결과물 만들고 싶은 서비스를 직접 구현하게 됩니다. 사람들이 방문하고 액션을 할 수 있는 웹 페이지를 제작 & 배포하는 것까지 진행됩니다. 여러분이 개발 경험이 있든

taling.me:443

 

Comments