css - 在 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 页面时,它工作正常。我希望你能向我解释我哪里出错了,谢谢。
解决方案
推荐阅读
- javascript - 当前日期到 React App 中的环境变量中
- git - git fsck:duplicateEntries:包含重复的文件条目 - 无法推送到 gitlab
- python-3.x - 如何从数据框的列中消除 3 个字母词或 4 个字母词
- gradle - Windows 上的 Gradle 执行命令
- google-chrome - W3C Pay(Bobpay 示例 chrome 扩展) - MAC OS - 无法重定向到 chrome 扩展。在 Windows 上工作
- java - 识别 java 中 gerDeclaredMethod 所需参数的类类型
- python - 对 pandas 数据框执行复杂搜索的最快方法
- flutter - 哪个小部件可以用作新路由中的根小部件(支持文本)而不覆盖 Flutter 中的整个屏幕?
- android - 如何正确使用 MediaPlayer 作为通知?
- python - Python:sqlite3.OperationalError:靠近“<”:语法错误(使用 html 源代码更新 sqlite3 字段)