[node.js] node.js 로 express 서버 구축 시 필요한 모듈 리스트

1. express

  • express 는 node.js 에서 web 서버 구축을 위해 꼭 필요한 모듈이다.

설치법

$ npm install express --save

사용법

const express = require('express')
const app = express()

app.get('/', (req, res) => {
  res.send("Hello World")
})

app.listen(3000, () => console.log("Listening on port 3000"))

2. nodemon

  • nodemon 은 node.js 코드가 변경될 때마다 web 서버를 자동으로 재시작 해준다.

  • 개발 편의성을 위해 꼭 필요하다.

설치법

$ npm install nodemon --save

사용법

  • node 대신에 nodemon 프로세스로 코드를 실행한다.

MacBook-Pro:express-demo server$ nodemon index.js
[nodemon] 1.18.9
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node index.js`
Listening on port 3000                         <====== 소스코드 수정 후 저장 시점에 web 서버가 재실행
[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
Listening on port 3000

3. joi

  • POST API 등으로 신규 값을 추가할 시 전달된 값의 유효성을 사전에 검사해야한다.

    ex> email 의 경우 @ 가 입력되어야 한다.

  • joi 는 입력된 값의 scheme 를 사전에 정의하여 값의 유효성을 검사 한다.

설치법

$ npm install joi --save

사용법

  1. 코드 상단에 joi 모듈 import

    const Joi = require('joi')
  2. post 함수 내 joi schema 및 validation 체크 함수를 입력한다.

    • 예시에서 전달될 값은 name 이라는 key 를 입력받으며, 3글자 이상 되어야 한다.

    • result 값으로 error 가 존재할 경우 res.status(400) 으로 400 Error 를 발생 시킨다.

    app.post('/api/courses', (req,res) => {
      const schema = {
          name : Joi.string().min(3).required()
      }

      result = Joi.validate(req.body, schema)
      console.log(result)

      if(result.error ){
          res.status(400).send(result.error)
          return
      }

      const course = {
          id : courses.length + 1,
          name : req.body.name
      }
      courses.push(course)
      res.send(course)
    })
  3. 유효하지 않은(3글자 미만) 값이 전달됐을 경우 result.error 에 의해 아래와 같이 출력된다.

    {
      "isJoi": true,
      "name": "ValidationError",
      "details": [
          {
              "message": "\"name\" length must be at least 3 characters long",
              "path": [
                  "name"
              ],
              "type": "string.min",
              "context": {
                  "limit": 3,
                  "value": "ch",
                  "key": "name",
                  "label": "name"
              }
          }
      ],
      "_object": {
          "name": "ch"
      }
    }

4. helmet

  • helmet 은 http header 의 보안 취약점을 보완해주는 middle ware 이다.

    • cspContent-Security-Policy 헤더를 설정하여 XSS(Cross-site scripting) 공격 및 기타 교차 사이트 인젝션을 예방합니다.

    • hidePoweredByX-Powered-By 헤더를 제거합니다.

    • hpkpPublic Key Pinning 헤더를 추가하여, 위조된 인증서를 이용한 중간자 공격을 방지합니다.

    • hsts는 서버에 대한 안전한(SSL/TLS를 통한 HTTP) 연결을 적용하는 Strict-Transport-Security 헤더를 설정합니다.

    • ieNoOpen은 IE8 이상에 대해 X-Download-Options를 설정합니다.

    • noCacheCache-Control 및 Pragma 헤더를 설정하여 클라이언트 측에서 캐싱을 사용하지 않도록 합니다.

    • noSniffX-Content-Type-Options 를 설정하여, 선언된 콘텐츠 유형으로부터 벗어난 응답에 대한 브라우저의 MIME 가로채기를 방지합니다.

    • frameguardX-Frame-Options 헤더를 설정하여 clickjacking에 대한 보호를 제공합니다.

    • xssFilterX-XSS-Protection을 설정하여 대부분의 최신 웹 브라우저에서 XSS(Cross-site scripting) 필터를 사용하도록 합니다.

설치법

$ npm install --save helmet

사용법

const Helmet = require('helmet')

app.use(Helmet)

5. morgan

  • morgan 은 express 내에서 로그 기록을 남겨주는 middleware 이다.

설치법

$ npm install --save morgan

사용법

const morgan = require('morgan')

app.use(morgan('short'))

실행 결과

Listening on port 3000
::1 - GET /api/courses/ HTTP/1.1 200 79 - 4.581 ms
::1 - GET /api/courses/ HTTP/1.1 200 79 - 0.564 ms
::1 - GET /api/courses/ HTTP/1.1 200 79 - 1.390 ms
::1 - GET /api/courses/ HTTP/1.1 200 79 - 0.227 ms

6. config

  • config 모듈은 application 에서 사용하는 설정 값을 공통된 파일을 통해 관리할 수 있도록 한다.

  • 시스템 환경 설정에 따라 default, development, production 등의 모드로 실행 가능하다.

설치법

$ npm install config --save

사용법

  • config 폴더 생성 후 default.json 파일 생성

    $ cat ./config/default.json
    {
      "name" : "My APP Configuration name"
    }
  • node.js 코드 내 아래와 같이 사용

    const config = require('config')

    console.log(config.get('name'))

실행 결과

My Gluster APP

7. winston

  • winston 은 node.js 의 대표적인 Logging 모듈이다.

  • winston 2.0 기준으로 정리 되어있다.

설치법

$ npm install winston --save

사용법

  • transports 설정을 통해 Console 및 File 에 로그 결과를 기록할 수 있다.

  • winston.log('로그 등급', '로그 metadata', '메시지') 형식으로 로그를 저장하면 된다.

var winston = require('winston');
winston.add(winston.transports.File, { filename: 'somefile.log' });
winston.log('info', 'Hello distributed log files!');
winston.info('Hello again distributed logs');

winston.level = 'debug';
winston.log('debug', 'Now my debug messages are written to console!');

winston.log('info', 'Test Log Message', { anything: 'This is metadata' });

실행 결과

  • somefile.log 내 아래와 같이 기록된다.

{"level":"info","message":"Hello distributed log files!","timestamp":"2019-02-21T02:53:30.870Z"}
{"level":"info","message":"Hello again distributed logs","timestamp":"2019-02-21T02:53:30.871Z"}
{"level":"debug","message":"Now my debug messages are written to console!","timestamp":"2019-02-21T02:53:30.871Z"}
{"level":"info","message":"Hello distributed log files!","timestamp":"2019-02-21T02:54:28.246Z"}
{"level":"info","message":"Hello again distributed logs","timestamp":"2019-02-21T02:54:28.247Z"}
{"level":"debug","message":"Now my debug messages are written to console!","timestamp":"2019-02-21T02:54:28.247Z"}
{"anything":"This is metadata","level":"info","message":"Test Log Message","timestamp":"2019-02-21T02:54:28.247Z"}


다른 카테고리의 글 목록

node.js 카테고리의 포스트를 톺아봅니다