【发布时间】:2012-06-16 22:51:13
【问题描述】:
我有一个标准的 node.js 静态文件服务器,我想用它来提供同一目录中的普通 html、js、css 和 jpg 文件(即典型的 HTML5 单页应用程序)。我希望节点服务器可以正确处理这个问题。我看到的不一样。
index.html 文件被提供,但随后的请求被丢弃(即它们永远不会到达服务器)。在我的 chrome 开发工具中,我看到如下内容:
GET http://projectcoho.cloudfoundry.com/css/coho.css http://projectcoho.cloudfoundry.com/:7
GET http://projectcoho.cloudfoundry.com/sencha-touch/sencha-touch-debug.js http://projectcoho.cloudfoundry.com/:8
GET http://projectcoho.cloudfoundry.com/coho-debug.js http://projectcoho.cloudfoundry.com/:8
但是,这些资源存在于服务器上,如果您直接输入它们的 URL,就可以访问它们。对于这些请求,我在 app.js 中的回调永远不会被调用(我可以这么说,因为这些文件永远不会调用 console.log。
这里是 app.js 文件:
var path = ".";
var port = process.env.VCAP_APP_PORT || 3000;;
var file = new(static.Server) (path, {
cache: 600
});
mime.define({
'text/css': ['css'],
'text/javascript': ['js'],
'image/jpeg': ['jpg', 'jpeg']
});
http.createServer(function (request, response) {
var uri = url.parse(request.url).pathname;
var filename = libpath.join(path, uri);
console.log("URI: " + request.url + " , filename: " + filename);
libpath.exists(filename, function (exists) {
console.log("Serving " + filename);
if (!exists) {
console.log("Not found");
response.writeHead(404, {
"Content-Type": "text/plain"
});
response.write("404 Not Found\n");
response.end();
return;
}
if (fs.statSync(filename).isDirectory()) {
filename += '/index.html';
}
var type = mime.lookup(filename);
file.serveFile(filename, 200, {'content-type' : type}, request, response);
});
}).listen(port);
我在这里错过了什么?
我正在使用节点 v0.6.15
【问题讨论】:
-
安德鲁——“端口”值是什么——即您的服务器是否正在侦听正确的端口?
-
文件系统权限是否允许您的服务器打开和读取文件?如果请求的文件是一个目录但该目录不包含
index.html文件会怎样? -
@MurrayMcDonald 在 CloudFoundry 上运行时,端口号由框架提供,但在 localhost 上运行时,端口为 3000。两种情况下的行为相同。
-
@sarnold 这是一个我还没有实现的案例。我很确定服务器会呕吐,但我正在尝试先解决更大的问题。
-
什么是“重写”提供给浏览器以将请求路由到正确端口的 URL?这是 CloudFoundry 本身“内置”的吗?