【问题标题】:My node.js server script is serving the index.html fine, but not the CSS or other static files我的 node.js 服务器脚本服务 index.html 很好,但不是 CSS 或其他静态文件
【发布时间】: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


【解决方案1】:

在 node.js 中发送文件并不是那么简单。我的框架中有一段代码

core.sendFile = function(filename, context)
{
    if (fs.exists(filename, function (exists)
    {
        if (exists) fs.stat(filename, function (err, stats)
        {
            if (err) core.catch_err(err);
            else if (stats && !stats.isDirectory())
            {
                var filestream = new fs.ReadStream(filename);
                var mimme = mime.lookup(filename);
                context.response.writeHead(200, {'Content-Type': mimme });
                filestream.pipe(context.response);
                filestream.on("error", function (err) { context.response.statusCode = "500"; context.response.end("Server error"); core.log("Server error while sending " + filename, "err"); });
                context.response.on("close", function () { filestream.destroy(); });
                core.logger.log("Sending file " + filename);
            }
        });
        else core.not_found(context);
    }));
}

这个想法是将文件作为流读写,并处理一些错误和关闭流。 “Core”只是一个库对象。

【讨论】:

    【解决方案2】:

    从您的网址中删除第一个 /,所以它应该是 stylesheet/style.css 而不是 /stylesheet/style.css

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-31
      • 1970-01-01
      • 2016-10-08
      • 1970-01-01
      • 2017-02-23
      • 1970-01-01
      • 1970-01-01
      • 2013-04-26
      相关资源
      最近更新 更多