【问题标题】:Refused to apply style from 'http://localhost:2000/cssFile/style.css' because its MIME type ('text/html')拒绝应用来自 'http://localhost:2000/cssFile/style.css' 的样式,因为它的 MIME 类型('text/html')
【发布时间】:2021-12-05 23:11:20
【问题描述】:

我目前正在尝试将我的 style.css 文件添加到由 express.js 呈现的 home.ejs 文件中

但我不断收到以下错误

Refused to apply style from 'http://localhost:2000/cssFile/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

我的文件结构是这样的

cssFile
 | style.css
views
 | htmlFile
 |   | home.ejs
index.js

这是我的快递代码

const express = require("express");
const app = express();
const path = require("path");
const mongoose = require("mongoose");
const Comments = require("./models/comments");

app.use(express.static(__dirname + "/public"));
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");

app.get("/", (req, res) => {
  res.render("htmlFile/home");
});

我的家.ejs:

...
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
      crossorigin="anonymous"
    />

    //buggy code
    <link rel="stylesheet" type="text/css" href="/cssFile/style.css" />
  </head>

我一直在尝试另一种解决方案,但我无法解决我的问题。

【问题讨论】:

  • 如果直接通过浏览器访问http://localhost:2000/cssFile/style.css,内容是否正确?

标签: javascript html node.js express ejs


【解决方案1】:

我的文件结构是这样的

cssFile
 | style.css
views
 | htmlFile
 |   | home.ejs
index.js

这是我的快递代码

... (all your other code)
app.use(express.static(__dirname + "/public"));

在这段 JavaScript 代码中,您告诉 express.static 您正在尝试从名为“public”的目录中提供静态文件,但该目录并不存在。如果您在浏览器中查看“网络”面板,您可能会看到为您提供了 404 页面,或者有时是不同的 HTML 文件。

尝试将文件结构更改为:

public
 | cssFile
 |  | style.css
views
 | htmlFile
 |   | home.ejs
index.js

【讨论】:

    【解决方案2】:

    如果您确实包含了正斜杠 (/public/),那么您可以只执行 href="/cssFile/style.css。我认为您不包含公用文件夹。

    另一种情况解决方案 将href转换为src

    <link rel="stylesheet" type="text/css" src="cssFile/style.css" />
    

    【讨论】:

      猜你喜欢
      • 2021-03-30
      • 2018-12-11
      • 2019-08-03
      • 2021-11-29
      • 2018-11-25
      • 1970-01-01
      • 2018-07-24
      • 2018-08-05
      • 1970-01-01
      相关资源
      最近更新 更多