【问题标题】:Express.js StaticPath problem | CSS not being applied on one Page while HBS not getting loaded on other PageExpress.js StaticPath 问题 | CSS 未应用到一个页面,而 HBS 未加载到其他页面
【发布时间】:2021-06-17 20:12:05
【问题描述】:

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

我要做什么:

  1. 提供 2 个 .hbs 文件 --> (index.hbs & about.hbs)
  2. 在两者中加载一个 Partial(标题)
  3. 应用一点 CSS 文件

发生了什么:

  1. CSS 已加载到 index.hbs,而部分未加载。
  2. 在加载部分内容时,about.hbs 上未加载 CSS。
  3. about.hbs 控制台窗口收到此错误: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.

设置静态路径:

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

文件夹结构:

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

【问题讨论】:

    标签: node.js express static handlebars.js


    【解决方案1】:

    您的问题与您如何使用 Express 注册静态资产路径有关。

    您的注册如下所示:

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

    这告诉 Express 在服务器上的“../public”文件夹中查找静态文件,其路径相对于 ../public 文件夹与请求的路径匹配。 p>

    例如,对“localhost:3000/css/homePageStyle.css”的请求将匹配服务器上位于“../public/css/homePageStyle.css”的文件。

    但请注意,“public”包含在 HTTP 请求路径中,因为它是 Express 查找静态文件的 root 文件夹。

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

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

    2. 使用 Express 注册静态资产路径时,指定“/public”作为虚拟路径前缀:app.use("/public", express.static(staticPath))

    接下来,您的主页不包含标题部分的原因是因为您的 index.hbs 文件甚至没有得到处理!您的“公共”文件夹中有一个“index.html”文件。当您的 HTTP 请求发往 localhost:3000/ 时,Express 会查看服务器的公共文件夹并找到与 index.html 匹配的内容,因此甚至无需执行“/”的 GET 处理程序即可返回。您需要删除该“index.html”文件,因为您不打算提供它。

    【讨论】:

    • 非常感谢先生,这解决了我的问题。我真的非常感谢你对我的问题的详细解释。我被困了2天。来自巴基斯坦的很多爱。
    • @ZaeemJaved:Shukriya。锦鲤。 (我希望我使用正确)
    • 哈哈哈。我的天啊。是的,您 100% 正确使用它们。
    猜你喜欢
    • 1970-01-01
    • 2016-07-05
    • 1970-01-01
    • 1970-01-01
    • 2014-01-03
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多