我创建了一个node.js服务器。当我使用端口3000进入localhost时,它只显示没有css或javascript的文本。我尝试过几种可以解决其他问题的解决方案。但他们并没有为我工作。
Node JS keep getting Failed to load resource error message
我的文件顺序是这样的
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]
答案 0 :(得分:8)
此:
__dirname + 'public'
应该是:
__dirname + '/public'
此外,您的html / css中的路径可能不正确,因为__dirname + '/public'
将是您的 root 。因此,除非您有一个目录__dirname + '/public/public'
,否则您必须更改html / css中的路径。
答案 1 :(得分:8)
问题解决了。
问题出在我的index.html文件中。最初我以为当我创建一个新文件夹并在其中放入所有css和js文件时,我需要添加“#public;' public'在所有的src中。喜欢这个
<script src="public/js/jquery.min.js"></script>
<script src="public/js/jquery.popline.js"></script>
但相反,我必须在没有&#39;公众&#39;像这样的文件夹
<script src="js/jquery.min.js"></script>
<script src="js/jquery.popline.js"></script>
并添加&#39; /&#39;建议使用__dirname + 'public'
到__dirname + '/public'
mscdex。
答案 2 :(得分:0)
在尝试了几个项目之后,我只想列出我的工作结果,以防它帮助其他任何人。
我曾尝试但未能为我工作的代码行:
app.use('/css', express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/public'));
app.use(express.static(path.join(__dirname, '../public')));
我的项目位于文件夹&#39; project&#39;其中包含&#39; public&#39;文件夹,&#39;观看&#39;文件夹和server.js文件。 Node,Express和Handlebars用于渲染页面。在&#39; public&#39;是一个文件夹&#39; css&#39;我的style.css文件保存在哪里。
在server.js上我使用了
var express = require('express');
var app = express();
app.use(express.static('public'));
在我的main.handlebars文件中查看&#39; &GT; &#39;布局&#39;我在
部分<link rel="stylesheet" href="/css/style.css">
有了这些,启动一个本地实例工作,没有“404&#39;加载样式表时出现错误消息。