【发布时间】:2014-03-11 08:37:30
【问题描述】:
我正在尝试根据教程编写 Node.js 项目,但 server.js 文件似乎无法正常工作:
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...");
});
当我转到我的 URL 时,会显示 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、node-modules 和 public 文件夹,public 文件夹有一个样式表目录和文件所在的 javascript 文件夹。
我的网络主机已设置为http://myURL.com/node/ 是端口 26353 绑定的位置(不知道这是否正确)。因此,如果我转到 http://myURL.com/node,我会看到 index.html 文件,但样式表或 javascript 都不起作用。
【问题讨论】:
-
你看过 expressjs 吗? expressjs.com/guide.html Express 内置了提供静态文件的功能。
-
这一行 filePath = '/public/' + request.url 应该是 filePath = '/public' + request.url (请注意,我从 public 中删除了尾部斜杠)。您还可以添加一堆“console.log('something')”来查看程序的哪一部分正在执行并验证它是否具有您期望的值。
-
顺便说一下,这是一个完整的 Node.js 中的 web 服务器示例gist.github.com/hectorcorrea/2573391
标签: javascript node.js