노드(NodeJS) 상에서 동작하는 웹 개발 프레임워크
Node.js 내장모듈인 http를 사용해 서버를 생성하고 http 요청을 처리하는 함수를 구현한다.
const http = require('http')
로 http라는 모듈을 import
(*require는 지금은 잘 사용되지 않는 문법)
http 통신 안에는 request와 response가 있다. -> 인자로 req, res를 받고, 함수를 실행시킨다.
createServer 안에 있는 callback 함수는 먼저 호출되는 createServer 메소드가 호출되면 실행된다.
server는 바꾸고 나면 ^C로 종료 후 다시 실행해야 한다.->nodemon 설치로 해결!
url => 사용자와 소통하는 주소
localhost => 프론트엔드 서버가 백엔드 서버에 접속할 때 사용
const { url, method } = req
request 안에 있는 url, method(GET or POST)를 변수에 할당한다.
라우팅을 직접 request 객체에서 url과 method 에 따라서 조건문으로 분기해서 다른 로직을 처리해야 한다.
앱의 규모가 커지면 조건문과 수많은 로직을 모듈화하기 어렵다.
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 === 'POST') 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.end(JSON.stringify({ message: 'this response answers to every request' }))
})
server.listen(8000, () => { console.log('server is listening on PORT 8000')}) // 5
const http = require('http')
const express = require('express')
const { sendPosts } = require('./sendPosts')
const app = express()
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(8080, () => {
console.log('server is listening on PORT 3000')
})
const sendPosts = (req, res) => {
res.json({
// express 덕분에 JSON.stringify 함수를 사용할 필요없이 response 객체의 json 메소드를 활용
products: [
{
id: 1,
title: 'node',
description: 'node.js is awesome',
},
{
id: 2,
title: 'express',
description: 'express is a server-side framework for node.js',
},
],
})
}
module.exports = { sendPosts } // routing.js 에서 사용하기 위해 모듈로 내보낸다.
http 모듈로 server를 생성 vs express로 server를 생성?
response를 반환할 때 사용하는 res.end()
, res.send()
, res.json()
의 차이점?
자주 사용하는 status 코드와 어떤 상황에서 사용하는지?
res.status(403).end()
res.status(400).send('Bad Request')
res.status(404).sendFile('/absolute/path/to/404.png')