JS/Node.js

📚 [node.js] Express에 html 렌더링 (EJS 사용)

Nyanggu 2023. 1. 12. 15:05

1. 터미널에서 아래 명령어를 입력하여  EJS 설치

npm install ejs

 

2. 폴더와 파일 만들기 

파일의 확장자는 .ejs로 해준다

 

3. server.js에 아래 코드를 추가해준다.

const express = require("express");
const ejs = require("ejs");         // ejs 모듈 요청
const app = express();
const port = 5000;

app.set("view engine", "ejs");      // 화면 engine을 ejs로 설정
app.use(express.static(__dirname + '/'));     // '/'로 기본 path 설정

app.get("/",(req,res)=>{

    res.render("index", {});
});

app.get("/view",(req,res)=>{

    res.render("view", {});
});

app.listen(port,()=>{
    console.log('서버실행 완료');

});

http://localhost:5000 로 접속하면 index.ejs를 띄워주고,

 

http://localhost:5000/view 로 접속하면 get방식을 이용해 view.ejs를 띄워주는 코드다.