우선, 프로젝트 폴더 안에 client라는 리액트 프로젝트는 이전글에서 만들어준 걸로 사용한다.
client와 형제 관계에 server라는 폴더 생성, 하단 그림과 같이 만들면 된다.
yarn global add typescript
yarn add express
yarn add ts-node
yarn add @types/node
yarn add @types/express
package.json 이 생성되는데, dependencies 아래에 하단 처럼 입력해준다. 하단 문서를 아예 복사해도 좋다.{
"dependencies": {
"@types/express": "^4.17.13",
"@types/node": "^17.0.18",
"express": "^4.17.3",
"global": "^4.4.0",
"ts-node": "^10.5.0",
"typescript": "^4.5.5"
},
"scripts": {
"start": "ts-node ./server/server.ts"
}
}
server 폴더에 하단처럼 파일/폴더들을 만들어준다.
test.ts에 들어갈 내용은 다음과 같다. 복사/붙여넣기 해주면 된다.const express = require("express");
const router = express.Router();
router.get("/", (req: any, res: any) => {
res.send("hi");
})
module.exports = router;
server.ts에 들어갈 내용은 다음과 같다. 복사/붙여넣기 해주면 된다.import express from 'express';
const app = express();
const test = require("./router/test");
app.use("/api", test);
const port: number = 5000;
app.listen(port, () => console.log(`${port}`));
yarn start 입력하여 터미널 창에 5000이 떠 있으면 성공! 이제 http://localhost:5000/api 로 가보자. hi 라는 말이 화면에 출력되면 타입스크립트로 서버 띄우기까지 성공한거다! nodemon과 concurrently를 설치해준다.nodemon : 개발 시 변경사항을 실시간으로 업데이트 해주기 위한 패키지로, --dev 명령어는 개발환경에서만 적용하기 위한 명령어다. 우린, 개발 시에만 nodemon을 사용할 것이므로, --dev 명령어를 추가하여 설치해준다.concurrently : 리액트 서버와 노드 서버를 동시에 실행 시키기 위한 모듈yarn add nodemon --dev
yarn add concurrently
package.json에 하단 스크립트들을 넣어준다. 다 넣고 yarn start 로 실행했을 때 http://localhost:5000/api 와 http://localhost:3000 둘 다 확인해보자. 잘 나오면 성공! 서버 설치는 끝났다. 이제, react 서버와 노드 서버를 연결시켜줘야 할 차례다.{
"dependencies": {
"@types/express": "^4.17.13",
"@types/node": "^17.0.18",
"concurrently": "^7.0.0",
"express": "^4.17.3",
"global": "^4.4.0",
"ts-node": "^10.5.0",
"typescript": "^4.5.5"
},
"scripts": {
"server": "cd server && nodemon server",
"client": "cd client && yarn start",
"start": "concurrently --kill-others-on-fail \"yarn server\" \"yarn client\" \"ts-node ./server/server.ts\""
},
"devDependencies": {
"nodemon": "^2.0.15"
}
}
client 폴더의 src 내에 setupProxy.js를 생성한다. client 폴더 위치에서 cmd를 열고 yarn add http-proxy-middleware를 입력해준다.setupProxy.js 에 하단 소스를 복사/붙여넣기 해주면 된다.const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = function (app) {
app.use(
createProxyMiddleware("/api", {
target: "http://localhost:5000",
changeOrigin: true,
})
);
};
yarn add axiosserver/router/test.ts와 client/src/App.tsx의 내용을 수정한다.server/router/test.tsconst express = require("express");
const router = express.Router();
router.get("/", (req: any, res: any) => {
res.send({ test : "hi"});
})
module.exports = router;
client/src/App.tsximport React, { useEffect } from 'react';
import axios from 'axios';
import './App.css';
function App() {
const callApi = async () => {
axios.get("/api").then((res) => console.log(res.data.test));
}
useEffect(() => {
callApi();
}, []);
return <div>테스트</div>
}
export default App;
yarn start로 실행시켜 본다. http://localhost:3000 에서 hi 라는 콘솔이 나오면 연동 성공!