(node.js) express로 서버 만들기

호두파파·2021년 7월 26일
0

Node.js

목록 보기
8/25

Express

Express.js는 node.js 환경에서 웹 어플리케이션 혹은 API를 제작하기 위해 사용되는 인기있는 프레임워크이다.

Express 설치하기

$ npm init // package.json 파일을 생성한다. 
$ npm install express // express 설치한다. 

Express로 서버만들기

const express = require('express')
const app = express()
const port = 3000;
app.get('/', (req, res) => { // get 메소드 일때,
  res.send('Hello World') // 응답 보내기 
})
app.listen(port, () => {
  console.log(`Example app listening at http://localhost:#{port}`)
})

Express를 사용하면 라우팅을 쉽게 구현할 수 있다.

라우팅이란?
라우팅은 URI(또는 경로) 및 특정한 HTTP 요청 메소드(GET, POST 등)인 특정 엔드포인트에 대한 클라이언트 요청에 애플리케이션이 응답하는 방법을 결정하는 것을 말한다.

순수 node.js로 구현한 것

const requestHandler = (req, res) => {
  if (req.url === '/message') {
    if (req.method === 'GET') {
       res.end(message)
    } else if (req.method === 'POST') {
      req.on('data', (req, res) => {
        //...
      })
    }
  }
}

Express로 만든 것

app.get('/message', (req, res) => {
  res.send(JSON.stringify(body));
});
app.post('/messages', jsonParser, function(req, res) {
  res.status(201);
  body.results.push(req.body);
  // body.results.push(JSON.parse(req.body));
  res.send(JSON.stringify(body));
});

app.method(PATH, HANDLER)와 같은 형식으로 라우팅이 가능하다.

  • appp은 express의 인스턴스이다.
  • method는 http 요총 메소드이다.
  • PATH는 서버에서의 경로이다.
  • HANDLER는 라우트가 일치할때 실행되는 함수이다.
profile
안녕하세요 주니어 프론트엔드 개발자 양윤성입니다.

0개의 댓글