Node.js express服务器无法读取HTML中的CSS文件

g6ll5ycj  于 12个月前  发布在  Node.js
关注(0)|答案(2)|浏览(170)

我已经做了一个node.js服务器,它的工作是发送一个图像和一个css文件沿着我的html网站。图像加载正常,但我在Firefox上弹出一个窗口,说样式表无法加载。为了调试,我把同样的css路径放在一个Iframe中,它打开得很好。
这是我的html

<!DOCTYPE html>
<html>
  <head>
    <title>Repo</title>
    <!-- DOESNT WORK!!! -->
    <style src="style.css" type="text/css"></style> 
  </head>

  <body style="margin: 0;">
    <img src="MazeBackground.png" alt="" srcset="">
    <iframe src="style.css" frameborder="0"></iframe>
    <!-- WORKS!?!?!?!? -->
  </body>
</html>

这是我的节点

const express = require("express");
const path = require("path");
const mime = require("mime");
const app = express();

app.get("/", (req, res) => {
  app.use(express.static('public'))
  res.sendFile(path.join(__dirname, "./public/index.html"));
});

app.listen(3000, () => console.log("server is listening on port 3000."));

我尝试将mimetype设置为text/css,然后自己发送css文件。我只是把一切都毁了。

mwecs4sa

mwecs4sa1#

你不需要<style>标签,它是内联CSS。您需要的是<link>标记。
HTML <link>标记需要href而不是src。因此,您需要相应地修改代码:

<link rel="stylesheet" href="style.css">

W3学校参考:w3schools reference

xa9qqrwz

xa9qqrwz2#

你必须像这样创建你的服务器:

const express = require("express");
const path = require("path");
const mime = require("mime");
const app = express();

app.use(express.static('public')) // put static middleware outside of get route
app.get("/", (req, res) => {
  
  res.sendFile(path.join(__dirname, "./public/index.html"));
});

app.listen(3000, () => console.log("server is listening on port 3000."));

相关问题