오늘은 express와 리엑트를 함께 연동해서 실행하는 방법의 대해 알아봅시다.
$ npx create-react-app myexampel
2.리엑트를 실행
$ npm start
리엑트는 포트 번호를 3000으로 자동 설정이 되고 node.js의 express는 다른 포트 번호를 설정해 주어야 충동이 일어나지 않는다.
express 설치
$ npm install express --save
body-parser 설치
$ npm install body-parser
서버에서 json 형식으로 데이터를 주고 받을거기 때문에 !
위에 4가지를 모두 설치 하였다면 !
먼저 App.js에서
import React from 'react';
import logo from './logo.svg';
import './App.css';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
username:null
};
}
render() {
const {username} = this.state;
return (
<div className="App">
<header className="App-header">
{username ? `Hello ${username}` : 'Hello World'}
</header>
</div>
);
;
}
}
export default App;
현재는 username이 없으므로 Hello World가 출력 됩니다.
그럼 이제 username을 서버에서 가져와 봅시다
root에 server라는 폴더를 만들고 server.js파일을 만듭니다.
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const port =process.env.PORT || 3001;
app.use(bodyParser.json());
app.use('/api', (req, res)=> res.json({username:'파피몬'}));
app.listen(port, ()=>{
console.log(`express is running on ${port}`);
})
이제 클라이언트 쪽에서 데이터를 받아와야 합니다.
App.js 에서 componentDidMount() 를 추가합니다.
componentDidMount() {
fetch('http://localhost:3001/api')
.then(res=>res.json())
.then(data=>this.setState({username:data.username}));
}
이상태에서 실행을 하면 오류가 뜹니다 !
cors 오류 !! 도메인이 다른곳에서 요청해 왔기 때문에 허용이 안되어서 오류가 납니다.
일단 ! server.js 에서 cors 를 사용할것이기 때문에 우선 설치.
$ npm install cors --save
server.js에
app.use(cors());
를 추가 하고 실행 시키면 서버에서 이름을 가져와서 HELLO 파피몬 이라고 보입니다.
npm start도 하고 node ./servers/server.js 도 하고 복잡하니깐 한번에 하는 방법을 알려드리겠습니당 !
우선 설치합니다.
$ npm install npm-run-all --save
packge.json을 열어
"scripts": { "start": "npm-run-all --parallel start:**", "start:client": "react-scripts start", "start:server": "node ./servers/server.js", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" },
script부분을 위와 같이 수정합니다.
그리고 npm start를 하면 서버와 리엑트 동시에 실행이 됩니다.