1. Node.js 프로젝트 dependency와 함께 생성하기

1장의 프로젝트 생성과정 및 index.js 생성을 마친 뒤, vs code 터미널에 다음 코드를 입력하여 install을 진행한다.

npm install express fs cors path body-parser mysql

index.js에 다음 코드를 입력한다.

const express = require('express');
const fs = require('fs')
const cors = require('cors');
const path = require('path');
const bodyParser = require('body-parser');

const app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(express.json())
app.use(cors())

const port = 4000;
app.listen(port, () => {
    console.log("Server listening on port", port)
})

package.json에 다음 코드를 추가한다.

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "test": "echo \\"Error: no test specified\\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.20.0",
    "cors": "^2.8.5",
    "express": "^4.18.1",
    "fs": "^0.0.1-security",
    "mysql": "^2.18.1",
    "path": "^0.12.7"
  }
}

터미널에서 npm start 명령을 실행한다.

2. nodemon(서버 refresh 모듈)

결과는 잘 실행되었는가? 그러나 서버가 돌아가는 과정에서 해당 코드를 수정해도 서버 자체는 refresh되지 않는다(포트 변경 등).

따라서 Ctrl+C를 눌러 서버를 잠시 닫고, 다음 dependancy를 터미널을 통해 하나 더 설치한다.

npm install nodemon

package.json에 추가했던 코드를 다음과 같이 변경한다.

"start": "nodemon index.js",

서버를 실행(npm start)하고, port번호를 바꿔보자. 잘 실행되는가?

3. MySQL과 연동하기

https://dev.mysql.com/downloads/installer/에서 MySQL을 다운로드 후 진행

VSCode에서 database.json 파일을 생성한 뒤 다음 코드를 입력한다.