본문 바로가기
react

node.js Express - react 서버 세팅

by dyyoo 2019. 10. 11.

Nodes.js express 복습하던 중, React도 공부도 같이 하고 싶은 마음에 토이프로젝트를 시작했다.

 

기본적인 구조는 create-react-app으로 생성한 폴더트리에서, server폴더 내에 express 프레임워크로 서버를 구성했다.

 

환경은 windows 10, vs code, node 10.대 버전

 

우선, 프로젝트 생성할 폴더 커멘드창에서 입력하면 아래 구조로 생성된다.

  -npm install -g yarn으로 yarn 명령어로 해도 된다. 

npx create-react-app <project name>

 

create-react-app기본구조 

 

babel, Webpack 등 모듈들이 설치가 되고, 여기서 Webpack 관련 설정을 하기위해 아래 명령어로 설정파일을 뽑아내줍니다.

npm run eject
//yarn eject

*eject관련 참고 블로그

https://blog.grotesq.com/post/691

 

 

 

eject를 하고 나면 아래 그림처럼 폴더가 추가된다.

 

여기까지 React 세팅을 완료하고, 이제 Express Framework환경을 세팅한다.

npm install --save express

* --save 명령어는 express를 설치하면서, package.json에 "express""^4.17.1", 이런식으로 설치기록을 남기는 명령어

  express모듈은 node_modules에 추가되는데,

예를들어 github에 프로젝트를 올릴때 부피가 큰 node_modules폴더는 제외하고 package.json 파일만 올려서

npm install 

다른사람이 프로젝트를 받은 후, 위 명령어로 모듈들을 한번에 설치할 수 있다.

 

 

아무튼 express를 설치한 후, src, config 폴더와 같은 레벨에 server와 같은 서버폴더를 생성.

 

그리고 project/server/server.js 와 같이 server.js 파일을 생성한 후, express 서버설정 코드를 입력한다.

 

기본적인 코드

'use strict';
const express = require('express');
const path = require('path');

const environments = require(path.join(__dirname, '..', 'server/config/environments'));

let app = express();

app.use(express.static(path.join(__dirname, '..', 'public/'))); 

const main = require('./routes/router');

app.use('/', main);

app.set('port', environments['port'] || process.env.PORT);
var server = app.listen(app.get('port'), function () {
    console.log('Express server has started on port : ' + server.address().port);
});

* 나는 server/config/environments.js 파일에 기본적인 서버 설정 정보를 넣고 꺼내 쓰도록 했다.

const environments = {
		host: "localhost",
        port: "8000"
}

module.exports = environments;

* 실제로는 DB정보나, redis정보 등을 넣었지만 여기선 필요 없어서 지웠다.

 

 

 

/server/routes/router.js  이 경로에 router.js를 추가한다.

const express = require('express');
const os = require('os');
const router = express.Router();

/* GET */
router.get('/api/getUserName', (req, res, next) => {
    res.send({ username: os.userInfo().username });
});

module.exports = router; 

 

여기까지가 express서버 세팅이다.

 

 

이제 react에서 서버의 http://localhost:8000/api/getUserName get요청을 보내기 위해 화면을 구성한다.

 

project/src/ 위치에 Header.js를 생성하고,

import React from 'react';

class Header extends React.Component {
    callApi(){
        fetch('/api/getUsername')
            .then((result) => {
                // Get the result
                // If we want text, call result.text()
                return result;
            }).then((jsonResult) => {
            // Do something with the result
            console.log(jsonResult);
        })
    }

    render() {
        return <div>
            <button onClick={() => this.callApi()}>
                Click here to call API
            </button>
        </div>;
    }
}

export default Header;

App.js에서 Header를 import하고,  넣고싶은 위치에 Header를 호출한다.

import Header from './Header'

function App() {
  return (
    <div className="App">
       '''
       <Header></Header>
       '''
    </div>
  );
}

export default App;

 

마지막으로 react를 실행시키면 기본적으로 localhost:3000 포트로 실행되고,

위 Header의 api는 'localhost:3000/api/getUserName'으로 가게 되는데 이걸 Express의 8000 포트로 가도록 해야한다.

 

package.json에서 아래 proxy를 추가해주면 8000포트로 가게된다.

"proxy" : "http://localhost:8000"

 

이제 /server 폴더에서 

npm start

으로 express서버를 실행하고,

상위 폴더에서 같은 명령어를 입력하거나, VS Code라면 f5로 react서버를 실행한다.

 

그리고 localhost:3000에서 버튼을 클릭하고 테스트하면 된다.

 

테스트는 브라우저 개발자모드에서 잘 통신되는지 확인할 수 있다.

 

----

 

spring boot, react, gradle로 개인 프로젝트를 하면서, react연습용으로 express에도 세팅했는데, 

초보 개발자라서 제대로 했는지는 모르지만 열심히 구글링으로 해결했다.

 

다음엔 spring에 react설정 한것도 남겨야겠다.

'react' 카테고리의 다른 글

[React] 기본정리  (0) 2019.11.04

댓글