Express.js StaticPath问题|HBS未加载到另一页面上时,CSS不在一页上应用 [英] Express.js StaticPath problem | CSS not being applied on one Page while HBS not getting loaded on other Page

查看:52
本文介绍了Express.js StaticPath问题|HBS未加载到另一页面上时,CSS不在一页上应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Express.js&设置了静态路径.

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

我要做什么:

  1. 提供2个.hbs文件->(index.hbs和about.hbs)
  2. 在两个文件中都加载一个局部文件(标题)
  3. 应用一点css文件

发生了什么事

  1. CSS加载到index.hbs上,而partial没有加载上.
  2. 部分加载的同时CSS尚未加载到about.hbs上.
  3. 在about.hbs控制台窗口上收到此错误:拒绝从"http://localhost:3000/public/css/homePageStyles.css"应用样式,因为其MIME类型('text/html')为不是受支持的样式表MIME类型,并且启用了严格的MIME检查.

设置静态路径:

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

文件夹结构:

完整的源代码链接: https://github.com/jeeemmyy/7.-Partials

推荐答案

您的问题与如何使用您的注册如下:

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

这是告诉Express在"../public"目录中查找相对于../public文件夹的路径 与请求的路径匹配的静态文件的服务器文件夹.

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.

例如,请求"localhost:3000/css/homePageStyle.css"将与服务器上"../public/css/homePageStyle.css"上的文件匹配.

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

但请注意,公开"包含在HTTP请求路径中,因为它是Express查找静态文件的 root 文件夹.

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.

要在模板中修复CSS引用,您需要执行以下任一操作:

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

  1. 删除公开"从模板中的样式链接href中获取:< link rel ="stylesheet"href =" ../../public/css/homePageStyles.css> 变为< link rel =" stylesheet"href ="/css/homePageStyles.css" .

指定"/public"在Express中注册静态资产路径时,将其作为虚拟路径前缀: app.use("/public",express.static(staticPath)).

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

接下来,您的首页不包含标题部分的原因是因为您的index.hbs文件甚至都没有得到处理!您有一个"index.html"在您的公开"文件中文件夹.当您的HTTP请求是对localhost:3000/的请求时,Express会在服务器的公用文件夹中查找并找到与index.html的匹配项,因此即使不对"/"执行GET处理程序,也可以返回该匹配项.您需要删除该"index.html"文件,因为您不打算提供它.

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.

这篇关于Express.js StaticPath问题|HBS未加载到另一页面上时,CSS不在一页上应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆