这是我当前的文件夹结构
css
app.css
js
app.js
node-modules
index.html
node-server.js
package.json
节点服务器托管index.html,但我无法弄清楚如何让app.js和app.css文件加载.
index.html加载它们:
<script src="js/app.js"></script>
<link rel="stylesheet" type="text/css" href="css/app.css"/>
这是错误消息:
Failed to load resource: the server responded with a status of 404 (Not Found)
2http://localhost:3000/css/app.css Failed to load resource: the server
responded with a status of 404 (Not Found)
我知道我需要或加载模块或什么,只是无法弄清楚是什么.
谢谢
解决方法:
原因
Node.Js不会自己为静态内容提供服务,必须定义路由以通过Node提供静态内容.
解决方案(手动):
var express = require('express'),
path = require('path'),
app = express();
app.get('/index.html',function(req,res){
res.sendFile(path.join(__dirname + '/index.html'));
});
app.get('/css/app.css',function(req,res){
res.sendFile(path.join(__dirname + '/css/app.css'));
});
app.get('/js/app.js',function(req,res){
res.sendFile(path.join(__dirname + '/js/app.js'));
});
app.get('/', function(req, res) {
res.redirect('index.html');
});
app.listen(8080);
改善方案:
目录结构:
public
css
app.css
js
app.js
index.html
码:
var express = require('express'),
path = require('path'),
app = express();
// Express Middleware for serving static files
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res) {
res.redirect('index.html');
});
app.listen(8080);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。