[Express] EJS용 Express 구성하기

Shin Hyun Woo·2022년 12월 5일
0
post-thumbnail

기본 세팅

npm init -y
npm i express
const express = require("express");
const app = express();
const port = 3000;

app.get("/", (req, res) => {
  res.send("Root routing");
});

app.listen(port, () => {
  console.log(`Starting server : localhost:${port}`);
});

템플레이팅 시작

템플레이팅을 위해 EJS를 사용하는데 Express에게 알려줘야한다.

EJS란?
Embedded JavaScript templating. JavaScript로 HTML 마크업을 생성할 수 있는 간단한 템플릿 언어이다.

먼저 EJS를 설치를 하고,

npm i ejs

app.set() 메서드로 view engineejs로 설정을 한다.

app.set("view engine", "ejs");

이 설정을 마치고 나면 새 Express 앱을 만들고 view engine을 사용할 때 Express는 views나 템플릿이 views 디렉토리 안에 있다고 가정한다.
왜냐하면 현재 작업 중인 디렉토리(process.cwd())에서 /views 디렉토리도 기본 설정이 되어있기 때문이다.

기본 Path를 일치시키기 위해 현재 디렉토리 위치에서 /views 디렉토리를 생성하고 디렉토리 내에 EJS 파일을 생성한다.

mkdir views
touch views/<fileName>.ejs

그리고 생성한 EJS 파일에 HTML 콘텐츠를 추가한다. EJS 파일에서 표준 HTML을 사용할 수 있기 때문에 원하는대로 HTML을 구성하면 된다.

이렇게 하면 간단한 템플릿이 완성이 된다.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Home</title>
  </head>
  <body>
    <h1>The Home Page</h1>
    <p>
      Lorem, ipsum dolor sit amet consectetur adipisicing elit. Nam nostrum
      deserunt, eos, debitis sequi vel saepe at aut quos non esse adipisci
      dolorem nihil error. Nostrum accusantium molestiae nesciunt. Maxime!
    </p>
    <p>
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Id expedita,
      illum cum ex culpa officia vel adipisci ut neque saepe voluptate
      similique, amet exercitationem, molestias cupiditate minus explicabo
      itaque unde!
    </p>
  </body>
</html>

이제 이 템플릿을 라우트 안의 res.send()대신 res.render()을 이용하면 문자열이 아닌 파일이나 템플릿을 보낼 수 있다.
res.render() 메서드는 첫번째 인자인 view(렌더링할 view 파일의 파일 경로인 문자열)를 렌더링하고 렌더링된 HTML 문자열을 클라이언트에 보내는 메서드이다.

또한 Path로 views/를 파일명에 적어주지 않아도 되는데 그 이유는 render() 메서드가 이미 views 디렉토리에 이미 존재한다고 가정하기 때문이다.

const express = require("express");
const app = express();
const port = 3000;

app.set("view engine", "ejs");

app.get("/", (req, res) => {
  res.render("<fileName>")
});
app.listen(port, () => {
  console.log(`Starting server : localhost:${port}`);
});

이렇게 작성하고 서버를 실행 후에 localhost:3000을 보면 렌더된 것을 볼 수 있다.

profile
untiring_dev - Notion 페이지는 정리 중!

0개의 댓글