본문 바로가기

공부기록/Node.js

[path is not defined]오류

path is not defied오류는 

path 를 require하지 않았기 때문에 나겠지만, 

지금 나의 오류는 달랐다.

 

path를 require했음에도 불구하고 path 오류가 난 것. 

 

const path = require("path");
const express = require("express");

const adminRoutes = require("./routes/admin");
const shopRoutes = require("./routes/shop");
const bodyParser = require("body-parser");
const productsController = require("./controllers/products");
// const expressHbs = require("express-handlebars");

const app = express();

//뷰엔진  ejs로 설정하기
app.set("view engine", "ejs");
app.set("views", "views");

app.use(express.static(path.join(__dirname, "public")));
//이미지, CSS 파일 및 JavaScript 파일과 같은 정적 파일을 제공

app.use(bodyParser.urlencoded({ extended: false }));

// /admin 경로일때
app.use("/admin", adminRoutes);

// /경로일때
app.use(shopRoutes);

//404 페이지
app.use(productsController.get404page);

//파일 http
app.listen(3001);

 

 

 

 

이유는... 간단했다. 

 

 

https://stackoverflow.com/questions/54878021/referenceerror-path-is-not-defined-ejs

 

ReferenceError: Path is not defined: EJS

The app runs for shop and admin routes but doesn't work for error route.Error routes was also in MVC format but i tested it without the architecture also. Below is the snippet of app.js from root

stackoverflow.com

 

다행스럽게도 나와 같은 강의를 듣는 사람이 스택오버플로우에 질문을 올린 것인데, 

답변은 아래와 같이 달렸다 :

 

"reason is that path is undefined so in the navigation.ejs can't find path's value so to solve it you should add it in the render function"

 

404페이지는 ejs 뷰엔진으로 렌더링하고 있었는데, 

정의되지 않은 path로 접속할 때 해당페이지를 렌더링하려고 했으나, 위의 답변과 같이

 

path가 정의되지 않고 있고, navigation.ejs가 path값을 찾지 못해 생긴 일이었다. 그러므로 404페이지를 렌더링할 때 path를 정의해주면 됐는데, 방법은 아래와 같다

 

exports.get404page = (req, res, next) => {
  // res.sendFile(path.join(__dirname, "views", "404.html"));
  res.status(404).render("404", { path:"Error" pageTitle: "notFound" });
};