const express = require("express")
const app = express()
// 인덱스 페이지 접속시 hellow express 출력됨
app.get("", (req, res) => {
res.send("Hello express")
})
// /help 페이지 접속시 출력
app.get("/help", (req, res) => {
res.send("Help page")
})
app.listen(3000, () => {
console.log("Server is up on port 3000")
}) //3000포트로 서버열기, 콜백함수로 열리면 콘솔 찍힘
app.get("/HTML", (req, res) => {
res.send("<h1>adsfasdf</h1>")
})
// array를 JSON 형태로 출력해준다
app.get("/JSON1", (req, res) => {
res.send({
name : "test",
test: "ttttt"
})
})
app.get("/JSON2", (req, res) => {
res.send([{
name: "ttt1"
}, {
name: "ttt2"
}])
})
const path = require("path")
//파일의 폴더 이름 출력
console.log(__dirname)
<<< asdfasdfasdf/asdfasdf/web-server/src
//파일 이름 출력
console.log(__filename)
<<< asdfasdfasdf/asdfasdf/web-server/src/test.js
console.log(path.join(__dirname, "../public"))
<<< asdfasdfasdf/asdfasdf/web-server/public
const path = require("path")
const express = require("express")
const app =express()
// 퍼블릭 폴더의 index.html위치
const publicDirPath = path.join(__dirname, "../public")
//index.html을 출력
app.use(express.static(publicDirPath))
// 위의 명령어가 실행 되어서 아래의 hellow express는 작동 안함
app.get("", (req, res) => {
res.send("Hello express")
})
생략
views폴더에 index.hbs 파일 생성
>>> npm i hbs@4.0.1
const app = espress()
// Using hbs as the default view engine requires
just one line of code in your app setup.
This will render .hbs files when res.render is called.
app.set("view engine", "hbs")
app.use(express.static(publicDirPath))
// views폴더의 인덱스.hbs를 랜더링함
app.get("", (req,res) => {
res.render("index", { //
title: "Weather APP",
name: "Andrew Mead"
})
})
views/index.hbs
<!DOCTYPE html>
<html>
<link rel="stylesteet" href="/css/stytles.css"
<script src="/js/app.js"></script>
<head>
<h1>{{title}}</h1> //위의 2번째 인자의 title과 name 사용
<p>Create by {{name}}</p>
</head>
<body>
</body>
</html>
hbs를 사용하기 위해선 views 폴더와 폴더안의 hbs 파일이 필요하다.
default를 커스터마이징 해보자
// Express config 경로 정의
const viewsPath = path.join(__dirname, ""../templates")
// handlebars engine 과 views 위치 셋업
app.set("view engine", "hbs")
app.set("views", viewsPath)
--templates
|
|--partials--header.hbs
|
|--views |
|--index.hbs
|
const partialsPath = path.join(__dirname, "../templates/partials")
//특정 경로의 hbs파일을 모두 불러온다
hbs.registerPartials(partialsPath)
>>> nodemone src/app.js -e js,hbs
// js와 hbs 파일의 변경사항을 감지
header.hbs 파일이 나머지 hbs파일의 타이틀이 되게 하려면
{{>header}}를 hbs 모든 파일 body 태그 사이에 넣어야한다
or {{>footer}}
// 설정하지 않은 모든 페이지
app.get("*", (req,res) =>{
res.send("My 404 page")
})