首页 > 解决方案 > 在 Express 中加载静态文件

问题描述

我一直在尝试让我的 node.JS 文件为我的 HTML 应用程序提供静态 CSS 和 JS 文件,但遇到了很大的困难(正在加载 HTML 文件,但没有样式)。从我的搜索看来,主要推荐的方法是将 Express 中间件添加到您的 node.JS 中,然后添加以下行:

app.use(express.static(path.join(__dirname, 'static/')));

在我继续深入之前,我将向您展示我的目录设置:

-static
    -images
        -favicon
            -favicon.png
        -logo.png
    -style
        -design.css
        -theme.css
        -w3.css
    -source
        -client
            -style.js
-node_modules
    -...
-index.html
-root.js
-package-lock.json
-...

“root.js”文件是我正在运行的 node.JS 文件,它为“index.html”页面提供服务,但我的 HTML 页面链接的所有 CSS 和 JS 文件都会出现这种错误......

The stylesheet http://localhost:8080/static/style/design.css was not loaded because its MIME type, "text/html", is not "text/css".

这是我的“index.html”中的一个示例,我在其中尝试链接到该 CSS 文件...

<link rel="stylesheet" type="text/css" href="static/style/design.css">

...这是在我的“root.js”文件中提供“index.html”的地方...

http.createServer(function (req, res) {
    fs.readFile('index.html', function (err, data) {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write(data);
        return res.end();
    });
}).listen(8080); 

我不太确定我哪里出错了,因为大多数关于该主题的指南似乎暗示当我在我的 node.JS 中添加神奇的 '__dirname' 行时,一切都是为了自行解决。当我通过在 Chrome 或 Firefox 中打开它在本地运行我的 HTML 页面时,它工作正常。我希望你能向我解释我哪里出错了,谢谢。

标签: cssnode.jsexpress

解决方案


推荐阅读