Programming/Node.js

[Node.js]http 모듈과 express 프레임워크간의 server 생성 방법 차이

중성자 2021. 12. 13. 20:34
728x90

Node.js의 http 모듈과 express 프레임워크로 server를 생성하는 방법중 가장 큰 차이점은 바로...

routingmodularization(모듈화)이다. 

 

앱이나 웹의 규모가 커지면 커질수록 코드는 복잡해 질수밖에 없는데 라우팅이나 모듈을 사용하지 않을 경우, 아래 코드와 같이 조건문으로 분기해서 다른 로직을 처리하게끔 해주어야 한다. 

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

const server = http.createServer((req, res) => {
  const { url, method } = req
  res.setHeader('Content-Type', 'application/json')

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

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

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

하지만 express 프레임 워크를 쓴다면, 아래와 같이 조금 더 간결하게 코드를 구성할 수 있게 된다. 

const http = require('http')
const express = require('express')
const { sendPosts } = require('./postings')

const app = express()
app.use(express.json())

app.get('/', (req, res) => {
  res.json({ message: '/ endpoint' })
})

app.post('/signup', handleSignUp) // 첫번째 인자에는 endpoint url 을 기입하고,
app.post('/login', handleLogin) // 각각의 요청에 대해 핸들링 하는 함수를 두번째 인자로 넣는다.
app.get('/products', sendPosts)

const server = http.createServer(app)

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