【问题标题】:Issue with linking a CSS file to a PUG file?将 CSS 文件链接到 PUG 文件时出现问题?
【发布时间】:2019-09-29 04:11:38
【问题描述】:

我正在尝试使用“链接”语法将 CSS 文件链接到 PUG 文件。当我尝试这样做时,我收到以下错误消息:

“拒绝应用来自 'http://localhost:3000/CSS/styles.css' 的样式,因为它的 MIME 类型 ('text/html') 不是受支持的样式表 MIME 类型,并且启用了严格的 MIME 检查。”

  • 我尝试过包含属性 type="text/css"。没用
  • 我尝试使用以下语法验证 css 文件路径是否正确:
    style
        include ../CSS/styles.css

这可行,并允许我确定 css 文件路径是否正确。但是,我想改用 index.pug 文件中所示的“link()”语法。

index.pug 头:

    head
        link(rel='stylesheet' href='../CSS/styles.css' type='text/css')

app.js 文件:

    const express = require('express');
    const http = require('http');
    const path = require('path');

    const app = express();
    const viewsPath = path.resolve(__dirname, "views");
    app.set("views", viewsPath);
    app.set('view engine', 'pug');

    app.get("/", function (request, response) {
        response.render("index");
    });
    http.createServer(app).listen(3000);

【问题讨论】:

  • 您是否尝试将 CSS 文件列为绝对路径而不是相对路径?
  • 当我尝试它时,我收到以下错误消息:Not allowed to load local resource: file:///D:/Google%20Drive/Projects/Dashboard/CSS/styles.css

标签: javascript css node.js express pug


【解决方案1】:

您需要将您的 css 文件作为static 提供服务。与 express 一起服务时,也最好使用absolute paths

假设您的 Dashboard 仅包含可以安全地暴露在网络上的文件。

app.use(express.static('Dashboard'))

// In your html, note absolute path
href='/CSS/styles.css'

您也可以通过指定挂载点来考虑virtual path

app.use('/static', express.static('Dashboard'))

// html
href='/static/CSS/styles.css'

【讨论】:

  • 我认为我不能使用 expres.static 模块提供 pug 文件。它适用于 .html 文件,但似乎不适用于 pug 文件,它只是说:“Cannot GET /”
  • 哦,我明白了。它现在可以工作了,我什至不必给出绝对路径。谢谢你。不太明白为什么它会这样工作,但它确实......
  • Don't really understand why it works,您需要通过提供底层静态文件来为客户端提供服务。 (希望很简单)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-29
  • 2019-06-26
  • 1970-01-01
  • 1970-01-01
  • 2014-04-18
相关资源
最近更新 更多