유튜브를 통해 Nodejs에 대해서 공부했고 결국에는 Express 사용하여 백엔드를 구성할 것이기 때문에 Express로 서버를 구성하는 절차에 대하여 적어보려고 한다.
나는 Node.js에서 초기에 설정을 할때 아래 3가지를 미리 설치했기 때문에 설치했다는 가정하에 시작한다.
npm install -g typesciprt
npm install -g ts-node
npm install -g nodemon
Express는 웹 및 모바일 애플리케이션을 위한 일련의 강력한 기능을 제공하는 간결하고 유연한 Node.js 웹 애플리케이션 프레임워크라고 공식 사이트에 소개가 되어있는 것을 알 수 있다.
서버를 실행할 경로에서 명령어 실행
npm init -y
tsc --init
두 파일은 함께 프로젝트의 설정 정보를 제공하며, TypeScript 프로젝트를 시작하는 데 필수적인 역할을 한다.
@types/node
express
@types/express
import express from "express";
const app: express.Application = express();
const hostname: string = "127.0.0.1";
const port: number = 5000;
app.get("/", (request: express.Request, response: express.Response) => {
response.status(200).send('<h3 style="color: blue">some html</h3>');
});
app.listen(port, hostname, () => {
console.log(`Express Server is started at http://${hostname}:${port}`);
});
코드 설명
라이브러리 불러오기
import express from "express";
express 모듈을 express라는 이름으로 import 문을 사용하여 불러온다. 이 모듈은 Express.js 프레임워크의 기능을 제공.
Express 애플리케이션 생성
const app: express.Application = express();
호스트네임과 포트 설정
const hostname: string = "127.0.0.1";
const port: number = 5000;
서버가 실행될 호스트네임 (hostname)과 포트 번호 (port)를 상수 변수에 저장
경로 설정(GET)
app.get("/", (request: express.Request, response: express.Response) => {
response.status(200).send('<h3 style="color: blue">some html</h3>');
});
서버 시작
app.listen(port, hostname, () => {
console.log(`Express Server is started at http://${hostname}:${port}`);
});
여기서 알 수 있는 Node.js와 다른 점은 http.createServer() 메서드를 호출하여 서버 객체를 생성하지 않는다는 것과 경로 지정을 if(request.url === '/' && request.mehtood === 'GET')과 같이 내부적으로 추가적인 코드를 작성하지 않는다는 것이다. 이러한 점만 봐도 더 편리하다.