[서버 배포] Express 사용하기, 5000포트가 계속 사용 중인 에러 문제, Path 라이브러리

AnSuebin·2022년 9월 4일
0

Express 사용하기

1. 기존 react 파일과 자매경로에 server 파일 만들어주기, serve폴더로 이동해주기

cd ./server/

2. npm 초기화 시켜주기

  • server 파일에 package.json이 생김
npm init -y

3. express 설치

  • package.json에 express가 생김
  • package-lock.json이 생김
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
  1. package.js에서 script에 start 명령어 추가
  "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 라이브러리 사용

  • path 라이브러리 설치
npm i path --save
  • path 라이브러리로 현재 경로와 상대 경로 join
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'))
})
  1. nodemon을 통해 서버 내용을 변경할 때마다 껐다 켰다 하는 것 안하게 하기
npm i nodemon --save
  1. nodemon으로 서버 실행
  • nodemon index.js
  • package.json에서 start: "nodemon index.js" 로 변경
profile
고객에게 명료한 의미를 전달하고, 명료한 코드를 통해 생산성 향상에 기여하고자 노력합니다.

0개의 댓글