Blog
JS Base
Express

기본 구조

npm init

아래 명령어 실행을 통해 package.json 파일을 생성한다.

npm init -y

기본 구조 생성

server.js라는 파일을 생성해서 아래와 같이 server의 기본 구조를 정의한다.

server.js
const express = require('express');
 
const PORT = 4000;
const app = express();
app.get('/', (req, res) => {
  res.send('Hello World');
});
 
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});

라우팅

:를 사용해서 라우트 파라미터를 받을 수 있다. 이 때 받아진 파라미터는 req.params의 동일한 이름으로 받아와진다.

const Users = [
  {
    id: 0,
    name: 'John',
  },
  {
    id: 1,
    name: 'Jenifer',
  },
]
 
app.get('/', (req, res) => {
  res.send('Hello World');
});
 
// 라우트 
app.get('/users', (req, res) => {
  res.send(Users);
});
 
// route 파라미터 
app.get('/users/:userId', (req, res) => {
  const userId = Number(req.params.userId);
  const user = Users.find((user) => user.id === userId);
  if(user) {
    res.status(200).send(user);
  }
  else {
    res.status(404).send('User Not Found');
  }
});

res.json() vs res.send()

res.json()과 res.send()의 동작에 대해서는 여기 (opens in a new tab)를 참고하면 된다.

  1. obj를 JSON 문자열로 변환한다.
// settings
  var app = this.app;
  var escape = app.get('json escape')
  var replacer = app.get('json replacer');
  var spaces = app.get('json spaces');
  var body = stringify(val, replacer, spaces, escape)
  1. Content-Type을 application/json으로 설정한다.
 // content-type
  if (!this.get('Content-Type')) {
    this.set('Content-Type', 'application/json');
  }
 
  return this.send(body);

위에서 알 수 있는 점은 외부에서 봤을 때는 아무런 차이가 없지만 res.send()를 사용하게 될 경우 내부에서 호출이 두 번 더 일어나기 때문에 성능상의 차이가 발생할 수 있다는 점이다.

res.send() vs res.end()

res.end()는 세션을 종료할 때 사용한다.
반드시 res.end()를 사용해줘야 하는 때는 데이터를 제공하지 않고 응답을 종료할 때 res.end()를 사용할 수 있고
res.send()나 res.json()을 사용하게 되면 알아서 세션이 종료가 된다.

  • res.send()와 res.end()의 차이

Content-Type : text/html; charset=utf-8
Etag : 생성됨.

Middleware

미들웨어 기능은 애플리케이션의 요청-응답 주기에서 요청 객체(req), 응답 객체(res), next 미들웨어 함수에 접근할 수 있는 기능입니다.

Express 애플리케이션은 본질적으로 일련의 미들웨어 기능 호출이라고 할 수 있다.