节点.js.为什么页面无法加载css和javascript文件

Node.js. Why is the page cannot load css and javascript file?

本文关键字:css 加载 javascript 文件 js 为什么 节点      更新时间:2023-09-26

我创建了一个节点.js服务器。当我使用端口 3000 进入本地主机时,它只显示文本,没有 css 或 javascript。我已经尝试了几种适用于其他解决方案的解决方案。但他们对我不起作用。

节点 JS 不断收到无法加载资源错误消息

带有快递的静态文件.js

无法获取 CSS 文件

我的文件顺序是这样的

server.js
index.html
 public
  css
   style.css

这是服务器的代码

var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');});
app.use(express.static(__dirname + 'public'));
app.listen(3000);

这些是错误

GET http://localhost:3000/ [HTTP/1.1 304 Not Modified 11ms]
GET http://localhost:3000/public/css/demo.css [HTTP/1.1 404 Not Found 10ms]
GET http://localhost:3000/public/css/themes/popclip.css [HTTP/1.1 404 Not Found 10ms]
GET http://localhost:3000/public/css/reveal.min.css [HTTP/1.1 404 Not Found 19ms]
GET http://localhost:3000/public/css/theme/default.css [HTTP/1.1 404 Not Found 12ms]
GET http://localhost:3000/public/css/jquery.dropdown.css [HTTP/1.1 404 Not Found 11ms]
GET http://localhost:3000/node_modules/socket.io/node_modules/socket.io-client/socket.io.js [HTTP/1.1 404 Not Found 10ms]
GET http://localhost:3000/public/js/jquery.min.js [HTTP/1.1 404 Not Found 29ms]
GET http://localhost:3000/public/js/jquery.popline.js [HTTP/1.1 404 Not Found 28ms]
GET http://localhost:3000/public/js/plugins/jquery.popline.link.js [HTTP/1.1 404 Not Found 28ms]

这个:

__dirname + 'public'

应该是:

__dirname + '/public'

此外,看起来您在html/css中的路径可能不正确__dirname + '/public'因为它将成为您的。因此,除非您有目录__dirname + '/public/public'否则您将不得不更改html/css中的路径。

问题解决了。

问题出在我的索引.html文件中。最初我认为当我创建一个新文件夹并在那里放入所有 css 和 js 文件时,我需要在所有 src 中添加"公共"。喜欢这个

<script src="public/js/jquery.min.js"></script>
<script src="public/js/jquery.popline.js"></script>

但相反,我只需要在没有这样的"公共"文件夹的情况下做到这一点

<script src="js/jquery.min.js"></script>
<script src="js/jquery.popline.js"></script>

并将"/"添加到__dirname + 'public'中,以__dirname + '/public'如MSCDEX建议的那样。

在尝试了一些项目后,我只想列出我的工作结果,以防它对其他人有所帮助。

尝试过但未能为我工作的代码行:

app.use('/css', express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/public'));
app.use(express.static(path.join(__dirname, '../public')));
我的项目位于文件夹"项目"中,其中包含"公共"文件夹

,"视图"文件夹和服务器.js文件。Node,Express和Handlebars用于呈现页面。在"公共"中有一个文件夹"css",其中保存了我的样式.css文件。

在服务器上.js我使用

var express = require('express');
var app = express();
app.use(express.static('public'));

在我的 main.handlebars 文件中的"视图">"布局"中,我在本节中有

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

有了这些,启动本地实例就可以了,加载样式表时没有"404"错误消息。