Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

node.js - Express.js StaticPath problem | CSS not being applied on one Page while HBS not getting loaded on other Page

I'm using Express.js & static path is set.

What i'm trying to do:

  1. Serve 2 .hbs files --> (index.hbs & about.hbs)
  2. Load a Partial in both of them (header)
  3. Apply a little css file

What's Happening:

  1. CSS is loaded on index.hbs while partial is not loaded on it.
  2. CSS is NOT loaded on about.hbs while partial is being loaded.
  3. Receiving this error on about.hbs console window: Refused to apply style from 'http://localhost:3000/public/css/homePageStyles.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

Setting Static Path:

const staticPath = path.join(__dirname, "../public")
app.use(express.static(staticPath))

Folder Structure:

enter image description here

Full Source Code Link: https://github.com/jeeemmyy/7.-Partials

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your issue has to do with how you are registering your static assets path with Express.

Your registration looks like this:

const staticPath = path.join(__dirname, "../public")
app.use(express.static(staticPath))

This is telling Express to look in the "../public" folder on the server for a static file whose path relative to the ../public folder matches that of the request.

For example, a request for "localhost:3000/css/homePageStyle.css" would match a file on the server at "../public/css/homePageStyle.css".

But note that "public" is not included in the HTTP request path because it is the root folder in which Express looks for static files.

To fix your CSS references in your templates, you would need to do either:

  1. Remove "public" from the style link href in your templates: <link rel="stylesheet" href="../../public/css/homePageStyles.css"> becomes <link rel="stylesheet" href="/css/homePageStyles.css">.

  2. Specify "/public" as a virtual path prefix when registering your static assets path with Express: app.use("/public", express.static(staticPath)).

Next, the reason your homepage is not including your header partial is because your index.hbs file is not even getting processed! You have an "index.html" file in your "public" folder. When your HTTP request is to localhost:3000/, Express looks in the server's public folder and finds a match with index.html and so returns that without even executing the GET handler for "/". You need to remove that "index.html" file, as you are not intending to serve it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...