Notice
Recent Posts
Recent Comments
Link
프로그래밍 공부방
[node.js/ejs] html파일에 다른 html 넣기 본문
HTML 파일에서 중복으로 사용되는 부분을 계속 코드를 작성해서 따로 넣어주기에는 비효율적인 일입니다.
따라서 ejs파일로 만들어서 html 파일 안에 다른 html 코드를 include 해주도록 하겠습니다.
1. app.js 코드
var fs = require('fs');
const ejs = require("ejs");
app.get('/', function(req, res){
fs.readFile('./views/index.ejs', "utf-8", function(error, data){
res.writeHead(200, {'Content-Type': 'text/html' });
res.end(ejs.render(data));
})
})
ejs를 사용하기 위해서 ejs 모듈을 require 해주세요~
당연히 ejs는 npm으로 설치를 해놓은 상태입니다!!
console.log(ejs.render(data))를 해봤을 때의 결과는 아래 사진과 같습니다.
렌더링이 잘 된 것을 확인할 수 있습니다.
저는 렌더링을 할 때 다른 값을 보내서 해당 html에 적용시킬 필요는 없기 때문에 data만 parameter로 넣어주었습니다.
render 함수를 통해 index.ejs에 있는 <% %>가 잘 적용이 되어서 결과를 출력합니다.

2. head.ejs 코드
<header class="main_title">
<h1 id="main_title">Plant Community</h1>
<div class="navbar_togglebBtn">
<i class="fas fa-bars"></i>
</div>
</header>
<nav class="navbar">
<ul class="navbar_menu">
<li><a href="#">식물 기본 정보</a></li>
<li><a href="plant_info_share.php">식물 정보 공유</a></li>
<li><a href="introduce_plant.php">내 식물 자랑</a></li>
</ul>
<ul class="navbar_icons">
<li><i id="my_info" class="fas fa-user-circle fa-lg"></i></li>
<input type="hidden" name="page_num" id="page_num" value="my_info">
</ul>
</nav>
head 파일은 확장자를 ejs말고 html로 해도 괜찮습니다. 경로 설정시에도 .html로 바꿔주시기만 하면 됩니다!
3. index.ejs 코드
<!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>index</title>
<script src="https://kit.fontawesome.com/e8028249b4.js" crossorigin="anonymous"></script>
</head>
<body>
<!-- 변경전 -->
<%- include('head.ejs') -%>
<!-- 변경후 -->
<%- include('C:\\Users\\~~~~~\\Desktop\\NodejsProject\\PlantServer\\views\\head.ejs') -%>
</body>
</html>
경로 설정 시 주의할 점
처음에는 코드 안에서 변경 전이라고 표시된 코드로 경로를 설정했습니다.
그랬더니 header파일을 찾지를 못하더라구요.

그래서 절대경로로 바꾸어서 경로 설정을 해주었더니 아래 사진처럼 잘 실행이 됐습니다!!
왜 변경 전 코드에서는 파일을 못 찾는지는 모르겠네요 ㅠㅠ...

'백엔드 > Node.js' 카테고리의 다른 글
[node.js] bcrypt를 이용한 패스워드 암호화 (회원가입 기능) (0) | 2022.07.28 |
---|---|
[node.js] httprequest 후 서버에서 request할 때 undefined 에러 해결방법 (0) | 2022.07.26 |
[node.js] 세션 생성 및 저장(mysql) (0) | 2022.07.20 |
[node.js] CORS 에러 해결 과정 (0) | 2022.07.08 |
[node.js] xml을 json형태로 바꾸고 값 출력 (0) | 2022.07.08 |