【问题标题】:Express.js cant apply stylesheetExpress.js 无法应用样式表
【发布时间】:2021-12-31 04:48:55
【问题描述】:

在运行我的 HTML+ExpressJS 代码时,我遇到了与 CSS 相关的问题。当我在浏览器中打开开发工具时,我看到Refused to apply style from 'https://localhost:5000/public/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

代码:

ExpressJS

const app = express();
app.use(express.static('public'));
app.get('/', (req,res) => {
    res.sendFile('/home/pi/website/index.html');
});

app.listen(5000, () => console.log('http://localhost:5000'));

HTML:

<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <title>homepage</title>
  <link rel="stylesheet" type="text/css" href="public/style.css" media="screen" />
  </head>
  <body>
    <h1 class=title>Hello!</h1>
    <h1 class=title>This page is running NodeJS on a Raspberry Pi 4 4GB</h1>
  </body>
</html>

【问题讨论】:

  • 您不必在样式表链接的路径中使用public
  • 样式表位于public
  • public 被认为是应用程序的根,因此,任何公开的内容都会自动供参考,不需要public 前缀。

标签: javascript html css express


【解决方案1】:

您的链接:

href="public/style.css"

不适用于

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

因为这将在您的服务器文件系统中的public/style.csspublic 目录中查找,这意味着它实际上正在寻找public/public/style.css,我假设您没有以这种方式设置文件系统。您没有准确显示 style.css 在您的服务器文件系统中的位置,但如果它直接在您指向 express.static()public 目录中,那么您应该使用:

href="/style.css"

【讨论】:

    猜你喜欢
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-08
    相关资源
    最近更新 更多