Search

Express를 사용해야 할 이유

Express를 사용해야 할 이유

Node.js는 HTTP 라이브러리를 내장하고 있어 자체적으로도 서버를 구현할 수 있다.
아래는 간단한 서버의 코드이다.
const http = require('http'); const app = http.createServer( (req, res) => { if (req.url === '/') return res.end('main') if (req.url === '/login) return res.end('login') }) const port = 3000; app.listen( port, () => { console.log(`server start on port ${port}`); })
Plain Text
복사
하지만 문제점이 하나 있다. 이 서버의 모든 요청은 createServer 내의 콜백함수를 통해 이루어진다는 것이다. 매 분기마다 콜백함수 내에 작성을 해야하니 코드가 복잡해지고 보기 어려워진다. 이러한 문제점을 해결하기 위해 Express를 사용하게 된다.
아래는 Express의 코드이다.
const express = require('express'); const app = express(); const port = 3000; app.get('/', (req, res) => { res.send('main'); }) app.get('/login', (req, res) => { res.send('login'); }) app.listen(port, () => { console.log('서버가 연결되었습니다!'); })
Plain Text
복사
app.get() 형태로 분기처리를 할 수 있게되어 코드 직관력이 눈에 띄게 개선된다. 그 외에도 미들웨어, 라우팅 등의 주요 기능 사용하기 용이하여 Express를 채택하게 된다.