본문 바로가기
Frontend/Project(개인 기록용)

작업중 만난 에러..

by Johnny_gon 2023. 6. 1.
728x90
반응형

 

server 코드

 
   const express = require("express");
   const app = express();
   //포트 로컬호스트랑 겹쳐서 5000변경
   const port = 5000;

   app.listen(port, () => {
     console.log(`Example app listening on port ${port}`);
   });

   app.get("/", (req, res) => {
     res.sendFile("../client/build/index.html");
   });
 

 

 

 

express 홈페이지에서 기본 틀 불러와서 server 세팅중에...

res.send('서버단 출력'); 은 5000번 포트에서 불러오기 성공했지만

client쪽 빌드 된 index.html 파일 보내려 하는데 에러가 뚜둥...

 

화면쪽 에러 표시

 

 

개발 도구창 에러

 

 

일단 화면쪽 에러 상단부에 힌트가 있어보인다.. 검색 고고

검색중... 전부 영어..  영어 공부 하자😂

 

 

출처 : https://itecnote.com/tecnote/node-js-express-js-path-must-be-absolute-or-specify-root-to-res-sendfile-error/

 

Node.js – Express.js “path must be absolute or specify root to res.sendFile” error – iTecNote

NOTE : This is NOT a duplicate question, I've already tried other answers to similar questions. I'm trying to render html files (Angular) but I'm having an issue. This works. app.get('/randomlink', function(req, res) { res.sendFile( __dirname + "/views/" +

itecnote.com

 

 

 

 

번역해서 보니 res.sendFile에서 직접 절대 경로를 사용해야 한다고 합니다. 

위에 솔루션은 두가지 방법을 소개하네요

저는 그나마 코드가 짧아보이는 1번 방법으로😀

 

path 모듈 설치하고 적용 고고!!   

npm i path --save

 

 

 

적용 코드

 
   const express = require("express");
   const app = express();
   const path = require("path");
   //포트 로컬호스트랑 겹쳐서 5000변경
   const port = 5000;

   app.use(express.static(path.join(__dirname, "../client/build")));
 
   app.listen(port, () => {
 
     console.log(`Example app listening on port ${port}`);
 
   });

   app.get("/", (req, res) => {
 
     res.sendFile(path.join(__dirname, "../client/build/index.html"));
 
  });
 

 

 

__dirname = server폴더 현재 경로

적용하니 에러는 없어졌는데 출력이 안되서 더 찾아보니 아래것도 추가해야 출력이 가능하다고 합니다..

 

app.use(express.static(...));

 

검색해보니 express.static 관련 좋은 글이 있어서 참조로 달아요 ( 잊어버릴 나를 위해 )

https://hwb0218.tistory.com/35

 

[Express.js] express.static() 정적파일 서비스

📌 미들웨어 express 프레임워크의 장점 중 하나로 미들웨어를 사용함. 미들웨어란 요청에 대한 응답 과정 사이에서 어떠한 동작을 하는 프로그램. 즉, express는 요청이 들어오면 그에 대한 응답을

hwb0218.tistory.com

 

 

 

728x90
반응형