짹뚜 스튜디오

[Node.js] Express 본문

개발 공부/nodejs

[Node.js] Express

짹뚜 2022. 2. 19. 16:12

Express

Express는 node.js의 웹 애플리케이션 프레임워크로 node.js로 웹 서버를 만들기 위한 다양한 라이브러리와 기능들을 제공하기 때문에 쉽고 간단하게 웹 서버를 구성할 수 있다.

서버 생성

const express = require('express');

const app = express();

app.listen(4000, () => {
  console.log('Server is Listening...');
});

라우팅

라우팅 (Routing)은 서버에서 클라이언트의 요청에 해당하는 method와 url에 따라 서버가 응답하는 방법을 결정하는 것이다. http 모듈로 라우팅을 구현한다면 다음과 같다.

const server = http.createServer((req, res) => {
  if (req.url === '/home') {
    if (req.method === 'GET') {
      // GET /home 요청이 왔을 때 로직
    } else if (req.method === 'POST') {
      // POST /home 요청이 왔을 때 로직
    }
  } else if (req.url === '/about') {
    if (req.method === 'GET') {
      // GET /about 요청이 왔을 때 로직
    }
  }
});

반면 express에서 라우팅은 쉽게 구현할 수 있다.

const express = require('express');

const app = express();

app.get('/home', (req, res) => {
    // GET /home 요청이 왔을 때 로직
});

app.post('/home', (req, res) => {
    // POST /home 요청이 왔을 때 로직
});

app.get('/about', (req, res) => {
    // GET /about 요청이 왔을 때 로직
});

app.listen(4000, () => {
  console.log('Server is Listening...');
});

Request

콜백 함수의 첫 번째 인자값으로 일반적으로 변수 이름을 req 또는 request로 한다.

 

  • req.params: url의 Parameter 값을 가지고 있다.
app.get('/home/:id', (req, res) => {
    console.log(req.params.id);
    // 만약 GET /home/1 요청을 했으면 1이 출력된다.
    // 만약 GET /home/2 요청을 했으면 2가 출력된다.
})
  • req.query: GET 방식으로 전달되는 쿼리 스트링을 가지고 있다.
  • req.body: http 메시지의 body 부분을 가지고 있다.
  • req.headers: http 메시지의 header 정보를 가지고 있다.

Response

콜백 함수의 두 번째 인자값으로 일반적으로 변수 이름을 res 또는 response로 한다.

 

  • res.status(<code>): http 응답 status code를 설정한다.
  • res.send(<body>): 클라이언트에 http 응답 메시지를 보낸다. 만약 <body>가 객체의 형태이면 내부적으로 res.json()을 호출한다.
  • res.json(<json>): http 응답 메시지 body를 json의 형태로 보낸다.

'개발 공부 > nodejs' 카테고리의 다른 글

[Node.js] http 모듈  (0) 2022.02.19
[Node.js] package.json  (0) 2022.01.31
[Node.js] NPM  (0) 2022.01.31
[Node.js] NVM  (0) 2022.01.03
Comments