express.js

jihyun·2021년 9월 18일
0

backend

목록 보기
3/13
post-thumbnail

express.js?

노드(NodeJS) 상에서 동작하는 웹 개발 프레임워크

withoutExpress

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

withExpress

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() 의 차이점?

  • res.send()
    HTTP response를 보내준다.(기본)
    send의 argument에 따라서 Content-type이 자동적으로 만들어진다.
  • res.json()
    JSON.stringify()를 사용해 객체, 배열, 문자 등 다른 타입의 값도 JSON 형식으로 보내준다.
    content-type 헤더를 application/JSON으로 고정하고,
    마지막에 res.send()를 호출한다.
  • res.end()
    보내줄 데이터가 없고 response를 끝내고 싶을 때 사용한다.
    (* 보내줄 데이터가 있는 경우 res.send() and res.json())

자주 사용하는 status 코드와 어떤 상황에서 사용하는지?

  • 2xx (성공)
    200(성공): 서버가 요청을 제대로 처리했다는 뜻이다. 이는 주로 서버가 요청한 페이지를 제공했다는 의미로 쓰인다.
  • 4xx (요청 오류)
    400(잘못된 요청): 서버가 요청의 구문을 인식하지 못했다.
    403(Forbidden, 금지됨): 서버가 요청을 거부하고 있다. 예를 들자면, 사용자가 리소스에 대한 필요 권한을 갖고 있지 않다. (401은 인증 실패, 403은 인가 실패라고 볼 수 있음)
    404(Not Found, 찾을 수 없음): 서버가 요청한 페이지(Resource)를 찾을 수 없다. 예를 들어 서버에 존재하지 않는 페이지에 대한 요청이 있을 경우 서버는 이 코드를 제공한다.
  • 5xx (서버 오류)
    502 (Bad Gateway, 불량 게이트웨이): 서버가 게이트웨이나 프록시 역할을 하고 있거나 또는 업스트림 서버에서 잘못된 응답을 받았다.
res.status(403).end()
res.status(400).send('Bad Request')
res.status(404).sendFile('/absolute/path/to/404.png')

0개의 댓글