RISK IT

[TIL10_23.1.18.] [Node] Express 초기 환경세팅 중 Express 분석 본문

IT/TIL

[TIL10_23.1.18.] [Node] Express 초기 환경세팅 중 Express 분석

nomoremystery 2023. 1. 18. 17:17
반응형

Express 공식 문서 API

Express 공식 문서 API에는 크게 express(), Application, Request, Response, Router로 나누어진다.

그 중에서도 각 항목들은 property와 method로 나누어진다.

(이걸 뭐라고 하지?)

westagram 프로젝트 소스코드에 사용한 property와 method를 분석해보자.

전체 소스코드

const express = require('express');

const cors = require('cors');
const morgan = require('morgan');

const dotenv = require('dotenv');
dotenv.config();

const { DataSource } = require('typeorm');

const myDataSource = new DataSource({
  type: process.env.TYPEORM_CONNECTION,
  host: process.env.TYPEORM_HOST,
  port: process.env.TYPEORM_PORT,
  username: process.env.TYPEORM_USERNAME,
  password: process.env.TYPEORM_PASSWORD,
  database: process.env.TYPEORM_DATABASE,
});

myDataSource
  .initialize()
  .then(() => {
    console.log('Data Source has been initialized!');
  })
  .catch((err) => {
    console.error('Error during Data Source initialization', err);
    myDataSource.destroy();
  });

const app = express();
const PORT = process.env.PORT;

app.use(cors());
app.use(morgan('dev'));
app.use(express.json());

// health check
app.get('/ping', (req, res) => {
  res.status(200).json({ message: 'pong' });
});

const start = async () => {
  try {
    app.listen(PORT, () => console.log(`Server is listening on ${PORT}!!`));
  } catch (err) {
    console.error(err);
  }
};

start();

Express에 해당하는 구문 분석

const express = require('express');

Express 모듈 불러오기

const app = express(); // express 실행

app.use(cors());
app.use(morgan('dev'));
app.use(express.json());

app.use([path,] callback [, callback...])

  • Mounts the specified middleware function or functions at the specified path: the middleware function is executed when the base of the requested path matches path.

즉, 위의 app.use(cors())cors()라는 함수를 callback 함수로 하여 마운트 하는 것을 의미한다.
app.use(morgan('dev'))app.use(express.json())도 각각 moran('dev'), express.json()의 함수를 callback 함수로 하여 마운트 하는 것을 의미한다.

mount란 컴퓨터 과학에서 저장 장치에 접근할 수 있는 경로를 디렉터리 구조에 편입시키는 작업을 말한다. 즉 여기에서는, 콜백함수를 사용가능한 상태로 만들어 실행시키는 것을 의미하는 것 같다.

// health check
app.get('/ping', (req, res) => {
  res.status(200).json({ message: 'pong' });
});

app.get(path, callback [, callback...])

  • Routes HTTP GET requests to the specified path with the specified callback functions.

즉, /ping 이라는 path를 찍으면 (req, res)라는 콜백함수 발동. 여기서는 arrow function으로 callback 함수가 작동한다.

res.status(code)

  • Sets the HTTP status for the response. It is a chainable alias of Node’s response.statusCode.
  • 응답에 대한 HTTP 상태를 보여준다. Node의 response.statusCode의 별칭에 해당한다.

200번대 상태코드는 성공에 대한 응답이다.

  • 200: OK
  • 201: Created
  • 202: Accepted
  • 204: No Content

등이 있다.

즉, 여기서는 HTTP 코드를 200으로 설정함으로써, 응답 성공 시에 대한 반응을 뒤에 나올 res.json()으로 설정한다.

res.json([body])

  • Sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using JSON.stringify().
  • The parameter can be any JSON type, including object, array, string, Boolean, number, or null, and you can also use it to convert other values to JSON.

즉, 여기서는 res.status(200)과 함께 HTTP 상태 코드가 200일 시 json의 형태로 message: "pong"을 출력한다.

const start = async () => {
  try {
    app.listen(PORT, () => console.log(`Server is listening on ${PORT}!!`));
  } catch (err) {
    console.error(err);
  }
};

app.listen([port[, host[, backlog]]][, callback])

  • Binds and listens for connections on the specified host and port. This method is identical to Node’s http.Server.listen().
  • If port is omitted or is 0, the operating system will assign an arbitrary unused port, which is useful for cases like automated tasks (tests, etc.).

즉, PORT에 해당하는 포트번호와 호스트와의 연결을 확인하여, 콜백함수를 실행시킨다. 만약 연결이 성공적으로 되었다면, console.log(Server is listening on ${PORT}!!);를 실행시킨다.

참고링크-express공식문서

반응형