오늘도 개발

Node.js에서 express 사용해보기 - 1. 개요(express, nodemon) 본문

웹 프로그래밍/Javascript

Node.js에서 express 사용해보기 - 1. 개요(express, nodemon)

Sueeeeeee 2022. 9. 22. 15:27

Express는 웹서버 개발을 편리하게 해주는 프레임워크이다.

Express를 사용하면 라우팅을 하기에도, 로직을 모듈화하기에도 용이하다.

 

1. Express 없이 서버를 개발하는 경우

1) 라우팅 없는 간단한 앱

1. 폴더 생성 후 새 프로젝트 생성

# 프로젝트가 위치할 디렉터리로 이동
mkdir test
cd test

# node package manager로 새 프로젝트를 만드는 명령(y는 yes)
npm init -y
# test 폴더 안에 package.json 생성됨.

2. 폴더 내 serverWithoutExpress.js 파일 생성

// serverWithoutExpress.js

// http라는 모듈을 가져와서 http 변수에 저장
// 자바스크립트의 import는 node.js에서 require로 사용
const http = require('http')

// createServer는 http 모듈에 내장된 함수, 콜백함수를 인자로 받음
// server 객체 생성 
const server = http.createServer((request, response) => { 
  console.log('request received')

  response.setHeader('Content-Type', 'application/json')
  response.end(JSON.stringify({ message: "Welcome to JUSTCODE server! Http server without express" }))
});

// 8000번 포트로 서버 켜기
// 요청이 들어오면 위의 함수 실행
server.listen(8000, () => {
  console.log('server is running on PORT 8000')
})

3. 터미널에서 파일 실행(서버 켜기)

node serverWithoutExpress.js
// server is running on PORT 8000

4. 요청 보내기

브라우저에서 localhost:8000 입력하고 엔터치거나

터미널에서 http localhost:8000 입력

=> 8000번 포트로 요청 감

=> 터미널에 request received 문구 뜸

 

2) 라우팅 있는 앱

여기까지는 기능이 하나밖에 없는 간단한 웹 서버를 만드는 과정이었다.

하지만 일반적인 웹사이트는 다양한 기능을 해야 하며,

각 기능에 대한 함수를 서버에서 만들어두어야 한다.

 

어떤 자원에 대해 각기 다른 함수를 실행하도록 하는 것을 라우팅이라고 한다.

method와 url을 설정하면 라우팅을 할 수 있다.

 

express 없이 node.js를 사용하면 다음과 같이 라우팅을 해야 한다.

 

<sendProducts.js>

const sendProducts = (res) => {
    res.end(
        JSON.stringify({
            products: [{
                id: 1,
                productName: 'tea'
            }, {
                id: 2,
                productName: 'icecream'
            }]
        })
    )
}

module.exports = {sendProducts}

<serverWithoutExpress.js>

const http = require('http')
const { sendProducts } = require('./sendProducts')

const server = http.createServer((req, res) => {
    const { url, method } = req 
    // const url = req.url
    // const method = req.method

    res.setHeader('Content-Type', 'application/json')

    if (url === '/signup' && method === 'POST') return res.end(JSON.stringify({message : '회원가입 완료'}))
    if (url === '/login' && method === 'POST') return res.end(JSON.stringify({message: '로그인 완료'}))
    if (url === '/products' && method === 'GET') return sendProducts(res)

    res.end(JSON.stringify({message: 'this response answers to every request'}))
})

server.listen(8000, () => {console.log('server is listening on PORT 8000')})

 

3) 단점

JSON.stringify()

자바스크립트로 백엔드를 만드는 경우에도 데이터를 JSON으로 변환해서 보내주어야 한다.

백엔드 언어가 꼭 자바스크립트라는 법이 없기 때문에 프론트엔드는 JSON만 이해할 수 있도록 되어있기 때문이다.

express 없이 개발하면 매번 JSON.stringify()로 데이터를 JSON으로 바꿔주어야 한다.

 

모듈화가 안 됨

한 함수안에서 모든 라우팅을 처리해야 한다.

일일이 if문으로 분기를 해야 해서 불편하다.

 

2. Express로 서버를 개발하는 경우

1. 폴더 생성 후 새 프로젝트 생성

# 프로젝트가 위치할 디렉터리로 이동
mkdir test
cd test

# node package manager로 새 프로젝트를 만드는 명령(y는 yes)
npm init -y
# test 폴더 안에 package.json 생성됨.

2. express 설치

npm install express --save

3. sendProducts.js 파일 생성

// req, res를 둘 다 인자로 넣어준다.
const sendProducts = (req, res) => {
    // JSON.stringify를 사용할 필요 없이 아래와 같이 작성하면 된다.
    res.json({
        products: [{
            id: 1,
            name: 'icecream'
        }]
    })
}

module.exports = {sendProducts};

3. serverWithExpress.js 파일 생성

const http = require('http') 
const express = require('express') // express 모듈 임포트
const { sendProducts } = require('./sendProducts')

// express로 앱 만들기
const app = express()
// app에 넣는 객체는 모두 json으로 만들어달라는 뜻
app.use(express.json())

// method를 app 뒤에 붙여줌, 인자로 (url, 콜백함수) 넣음
app.get('/ping', (req, res) => {
    res.json({message: 'pong'})
})
app.post('/signup', (req, res) => {res.json({message : 'signup success'})})
app.post('/login', (req, res) => {res.json({message : 'login success'})})
app.get('/products', sendProducts)

const server = http.createServer(app)

server.listen(8000, () => {
    console.log('server is listening on PORT 8000')
})

 

3. Nodemon 패키지 활용하기

Node에서는 코드 수정 사항이 자동으로 서버에 반영되지 않음.

Nodemon 사용하면 자동으로 반영시킬 수 있음. 

 

1. 설치

sudo npm install -g nodemon

2. 실행

nodemon 앱이름
// 예: nodemon serverWithExpress.js