『Node.js』 CSS등의 파일이 적용 안될 때

High-PO·2022년 4월 22일
2

Node.js

목록 보기
2/4
post-thumbnail

결론부터

HTML에서 경로를 작성 할때 경로 앞에 있는 적용된 정적경로를 지워주면 된다.

개요

로컬에서 실행한 html에서는 경로가 잘 적용되었지만 Node.js상에서 html을 실행시키면 css나 img, javascript가 작동하지 않는 일이 발생하였다.

코드

index.html

...
    <!-- Bootstrap core CSS -->
	<link href="/public/assets/dist/css/bootstrap.min.css" rel="stylesheet">

...
    <!-- Custom styles for this template -->
    <link href="/public/css/product.css" rel="stylesheet">
  </head>
  <body>

server.js

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

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

app.get("/", function(req, res){
  res.sendFile(__dirname + "/html/index.html");
});

app.listen(8080, () => {
  console.log("IHMS ON");
})

문제점 및 해결 방법

위 코드상에 보이는 static경로를 지정해주는 app.use부분을 보게 되면 public이라는 부분을 정적파일로 이미 지정을 해두었다.

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

그럼 이제 index.html부분을 확인을 해보면 아래와 같이 경로를 public이라는 경로를 함께 주었다.

...
	<link href="/public/assets/dist/css/bootstrap.min.css" rel="stylesheet">
...

이렇게 될 경우 PC가 해석할 때 경로는 /public/public/assets/... 이런식으로 해석을 하게된다.

올바르게 바뀐 코드

...
	<link href="assets/dist/css/bootstrap.min.css" rel="stylesheet">
...

위 코드와 비교해보면 무엇이 달라진지 알 수 있다.

후기

까먹지 말자..!

profile
반갑습니다 :)

0개의 댓글