我想从教程中编写一个Node.js项目,但server.js文件似乎不是正常工作:我的node.js服务器脚本服务于index.html,但不是CSS或其他静态文件
var http = require('http');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var cache = {};
function send404(response) {
response.writeHead(404, {'Content-Type': 'text/plain'});
response.write('Error 404: not found');
response.end();
}
function sendFile(response, filePath, fileContents) {
response.writeHead(
200,
{"content-type": mime.lookup(path.basename(filePath))}
);
response.end(fileContents);
}
function serveStatic(response, cache, absPath) {
if (cache[absPath]) {
sendFile(response, absPath, cache[absPath]);
} else {
fs.exists(absPath, function(exists) {
if (exists) {
fs.readFile(absPath, function(err, data) {
if (err) {
send404(response);
} else {
cache[absPath] = data;
sendFile(response, absPath, data);
}
});
} else {
send404(response);
}
});
}
}
var server = http.createServer(function(request, response) {
var filePath = false;
if(request.url == '/') {
filePath = 'public/index.html';
} else {
filePath = '/public/' + request.url;
}
var absPath = './' + filePath;
serveStatic(response, cache, absPath);
});
server.listen(26353, function() {
console.log("Listening...");
});
当我去我的网址显示index.html的内容,但显示没有在index.html的样式或附加文件,我得到:
GET http://myURL.com/stylesheet/style.css 404 (NOT FOUND)
这里是我的index.html:
<html>
<head>
<title>Chat</title>
<link rel='stylesheet' href='/stylesheet/style.css'></link>
</head>
<body>
<div id='content'>
<div id='room'></div>
<div id='room-list'></div>
<div id='messages'></div>
<form id='send-form'>
<input id='send-message' />
<input id='send-button' type='submit' value='Send' />
<div id='help'>
Chat commands:
<ul>
<li>.....</li>
</ul>
</div>
</form>
</div>
<script src='/socket.io/socket.io.js' type='text/javascript'></script>
<script src='http://code.jquery.com/jquery-1.8.0.min.js' type='text/javascript'></script>
<script src='/javascript/chat.js' type='text/javascript'></script>
<script src='/javascript/chat_ui.js' type='text/javascript'></script>
</body>
</html>
我不知道什么是错的。
我的项目目录有server.js,节点模块和公共文件夹,公共文件夹有一个样式表目录和javascript文件夹,其中的文件是。
我的网络主机已设置,以便http://myURL.com/node/是端口26353绑定到(不知道这是否是正确的词)。所以,如果我去http://myURL.com/node我看到index.html文件,但没有样式表或JavaScript的作品。
你看过expressjs吗? http://expressjs.com/guide.html Express内置了用于提供静态文件的功能。 –
这行filePath ='/ public /'+ request.url应该是filePath ='/ public'+ request.url(注意我删除了公开的尾部斜杠)。您还可以添加一堆“console.log('something')”来查看您的程序的哪个部分正在执行,并验证它是否具有您期望的值。 –
顺便说一下,这里是Node.js中web服务器的完整示例https://gist.github.com/hectorcorrea/2573391 –