1. 기존 react 파일과 자매경로에 server 파일 만들어주기, serve폴더로 이동해주기
cd ./server/
2. npm 초기화 시켜주기
npm init -y
3. express 설치
npm i express --save
4. index.js파일 만들고 아래 내용 붙여 넣어주기
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
// 서버를 열고
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
//요청이 왔을 때 응답 구현
app.get('/', (req, res) => {
res.send('Hello World!')
})
// 기본포트가 3000이기 때문에 5000으로 변경
const port = 5000
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js"
},
6. 5000번 포트가 되지 않을 때 문제(address already in use :::5000)
7. control + c 로 서버 꺼줄 수 있음
8. 기존 react 파일 서버로 이동하여, build 해주기
npm run-script build
9. server 파일로 돌아와 index.js에 react파일에서 빌드해준 파일 입력
app.get('/', (req, res) => {
res.sendFile('../PostSite/build/index.html')
})
10. 다만, 현재경로를 보여줘 상대 경로가 무엇인지 보여줘야함, Path 라이브러리 사용
npm i path --save
const path = require("path")
app.use(express.static(path.join(__dirname, '../PostSite/build')))
app.get('/', (req, res) => {
// path라이브러리로 현재 경로와 상대 경로 join
res.sendFile(path.join(__dirname, '../PostSite/build/index.html'))
})
=> index.js 최종
const express = require('express')
// Path 라이브러리 사용
const path = require('path')
const app = express()
// 기본포트가 3000이기 때문에 5000으로 변경
const port = 5000
//추가해주기
app.use(express.static(path.join(__dirname, '../PostSite/build')))
// 서버를 열고
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
//요청이 왔을 때 응답 구현
// req : 요청
// res : 응답
// '/'로응답
app.get('/', (req, res) => {
// path라이브러리로 현재 경로와 상대 경로 join
res.sendFile(path.join(__dirname, '../PostSite/build/index.html'))
})
npm i nodemon --save
nodemon index.js
start: "nodemon index.js"
로 변경