为什么只有当通过服务器访问 HTML 文件时我的 CSS 才不被应用?

问题描述 投票:0回答:1

我的 CSS 按预期工作,但通过服务器加载时它不再工作。

编辑: 好的,我会再试一次,我已将所有内容简化为一个简单的 Express 服务器、一个 html 文件和一个 css 文件:

import express from "express";
import bodyParser from "body-parser";
import { dirname } from "path";
import { fileURLToPath } from "url";

const app = express();
const port = 3000;
const __dirname = dirname(fileURLToPath(import.meta.url));

app.use(bodyParser.urlencoded({ extended: true }));

app.listen(3000, () =>{
    console.log(`server listening on port ${port}`);
});

app.get("/", (req, res) =>{
    res.sendFile(__dirname + "/index.html");
});
body{
  background-color: blue;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>test</title>
</head>

当 HTML 文件尝试应用 css 时,我收到错误:

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

我在另一页上读到,当找不到文件时有时会发生这种情况。在主项目上,html 无法找到我提供的任何 css、图像或 js。

我觉得必须有一个简单的解释 - 我对此很陌生,并且通过我的教育运行了大量的 Express 服务器,以前从未见过这种情况。

html css
1个回答
0
投票

我在设置服务器时也遇到了这个问题!您遇到的问题是您在服务器端代码中仅提供 HTML 文件,其中不包括 CSS 和图像文件。我想 Ry- 可能在评论中提到过这一点。要解决此问题,只需在服务器端 JS 中添加一行:

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

这会将您的服务器指向所有静态文件,并允许您的 HTML 文件访问它们。确保

public
指向您要提供的所有文件所在的目录。

根据您提供的代码片段,您的最终代码应如下所示:

import express from "express";
import bodyParser from "body-parser";
import { dirname } from "path";
import { fileURLToPath } from "url";

const app = express();
const port = 3000;
const __dirname = dirname(fileURLToPath(import.meta.url));

app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public')) // This is the only changed line

app.listen(3000, () =>{
    console.log(`server listening on port ${port}`);
});

app.get("/", (req, res) =>{
    res.sendFile(__dirname + "/index.html");
});
body{
  background-color: blue;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>test</title>
</head>

有关更多信息,请查看 Express.js 网站上的 文档

© www.soinside.com 2019 - 2024. All rights reserved.