首页 > 解决方案 > 在 Express.js 中添加子站点时 CSS 无法正确发送

问题描述

请记住,我是 Express 等方面的新手。

我有一个问题,我称之为“子站点”的 CSS 无法加载。

子站点是指至少有 2 个斜杠的地址,例如domain.com/site/subsite.

我正在使用 Express 应用程序:

const express = require(`express`);
const app = express();
const port = 80;

app.use(express.static(__dirname + `/public_html`)); // For serving CSS & JS to websites

app.get(`/`, (req, res) => { // Root domain
    res.sendFile(__dirname + `/public_html/index.html`)
});

app.get(`/website`, (req, res) => { // Another, example site
    res.sendFile(__dirname + `/public_html/website1.html`)
});

app.get(`*`, (req, res) => { // For 404
    res.sendFile(__dirname + `/public_html/404.html`, 404)
});

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

在这种情况下,CSS & JS 工作得很好。

但是,当我这样做时:

app.get(`/website/subsite`, (req, res) => { // A website with 2 slashes in it
    res.sendFile(__dirname + `/public_html/website2.html`)
});

即使没有更改正常的代码,CSS 或 JS 也不会随网站发送。

我还应该提到我的所有文件都在public_html文件夹中:

ProjectDirectory:
  |> server.js
  |> package.json
  |> package-lock.json
  |> public_html/:
    |> index.html
    |> website1.html
    |> website2.html
    |> css/:
      |> index.css // Corresponding css file to index.html
      |> website1.css
      |> website2.css
    |> js/:
      |> ...

每个html页面都有一个link标签: <link rel="stylesheet" href="./css/*correct file*.css">

当您键入 /website/ 而不仅仅是 /website 时,也会发生这种情况

加载子网站时弹出的错误:

拒绝应用来自 'URL' 的样式,因为它的 MIME 类型 ('text/html') 不是受支持的样式表 MIME 类型,并且启用了严格的 MIME 检查。我认真尝试了许多解决方案,但找不到合适的解决方案。

如果您不理解我的问题,请解释如何在 ExpressJS 中正确包含 css 和 js 文件。

感谢所有的帮助!

标签: javascripthtmlcssnode.jsexpress

解决方案


问题是您的 html 文件中的这一行:<link rel="stylesheet" href="./css/*correct file*.css">. 由于./css/[...] ,相对于当前 URL 提交了对 css 文件的请求。更改该行以使用来自根域的绝对路径,如下所示<link rel="stylesheet" href="/css/*correct file*.css">(注意第一个斜杠前面缺少的点)。

这也解决了 的问题/website/,因为尾部斜杠将 css 的路径更改为/website/css/website1.css,这无法通过 express 解决。

服务器.js

const express = require(`express`);
const app = express();
const port = 80;

app.use(express.static(__dirname + `/public_html`)); // For serving CSS & JS to websites

app.get(`/`, (req, res) => { // Root domain
    res.sendFile(__dirname + `/public_html/index.html`)
});

app.get(`/website`, (req, res) => { // Another, example site
    res.sendFile(__dirname + `/public_html/website1.html`)
});

app.get(`/website/subsite`, (req, res) => { // A website with 2 slashes in it
    res.sendFile(__dirname + `/public_html/website2.html`)
});

app.get(`*`, (req, res) => { // For 404
    res.sendFile(__dirname + `/public_html/404.html`, 404)
});

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

示例 website1.html

<!DOCTYPE html>

<head>
    <link rel="stylesheet" href="/css/website1.css">
</head>

</html>

推荐阅读