我整理了一个基本的Node应用程序,并试图避免不必要的依赖(最值得注意的是express
)用于教育目的。但是,我一直在尝试提供静态文件,如图像或CSS。出于安全考虑,我选择使用node-static over编码我自己的版本,但我似乎无法正确地解决问题。
文件结构
index.js
router.js
server.js
requestHandlers.js
package.json
views/
index.jade
public/
image.jpg
索引
var server = require("./server"),
router = require("./router"),
requestHandlers = require("./requestHandlers");
var handle = {
"/": requestHandlers.index
};
server.start(router.route, handle);
requestHandlers
var jade = require("jade");
function index(response) {
response.writeHead(200, {"Content-Type": "text/html"});
var body = jade.renderFile("views/index.jade");
response.write(body);
response.end();
}
exports.index = index;
服务器
var http = require("http"),
url = require("url"),
static = require("node-static"),
port = Number(process.env.PORT || 8888);
var fileServer = new static.Server("./public");
function start(route, handle) {
function onRequest(request, response) {
// NODE STATIC CODE - NOT WORKING
request.addListener('end', function () {
fileServer.serve(request, response);
}).resume();
// ROUTE HANDLING - WORKING
var pathname = url.parse(request.url).pathname;
route(handle, pathname, response);
}
http.createServer(onRequest).listen(port);
}
exports.start = start;
路由器
function route(handle, pathname, response) {
if (typeof handle[pathname] === 'function') {
console.log("Request handler " + pathname + " was called.");
handle[pathname](response);
} else {
console.log("No request handler found for " + pathname);
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not Found");
response.end();
}
}
exports.route = route;
最后,我的索引文件调用了img(src="public/image.jpg")
,尽管我还尝试了image.jpg
和public/image
。正在调用和处理/
路由,但是当索引文件尝试加载图像时,我的请求处理程序的else
块被命中(正如预期的那样,因为我没有路由它没有其他任何事情发生。有人可以解释在这种情况下使用node-static
的正确方法吗?