为什么不是“/”在node.js中提供index.html?

我想写一个函数,返回主页, index.html 。 但是,当我删除线

 requestpath += options.index 

我得到以下错误:

 500: encountered error while processing GET of "/" 

没有这一行,请求不会是localhost:3000/ ,这应该为index.html

我猜测它最后与fs.exist函数有关,但我不确定。

 var return_index = function (request, response, requestpath) { var exists_callback = function (file_exists) { if (file_exists) { return serve_file(request, response, requestpath); } else { return respond(request, response, 404); } } if (requestpath.substr(-1) !== '/') { requestpath += "/"; } requestpath += options.index; return fs.exists(requestpath, exists_callback); } 

options等于

 { host: "localhost", port: 8080, index: "index.html", docroot: "." } 

fs.exists检查文件系统中是否存在文件。 由于requestpath += options.index正在改变/ to /index.html ,没有它fs.exists不会find一个文件。 ( /是一个目录,不是文件,因此是错误。)

这可能看起来很混乱,因为localhost:3000/应该服务于index.html 。 在网页上, /index.html缩写(除非您将默认文件设置为其他内容)。 当你询问/ ,文件系统会查找index.html ,如果存在的话,它会提供它。

我会改变你的代码:

 var getIndex = function (req, res, path) { if (path.slice(-1) !== "/") path += "/"; path += options.index; return fs.exists(path, function (file) { return file ? serve_file(req, res, path) : respond(req, res, 404); }); } 

尝试和匿名callback,除非你知道你要在别处使用它们。 在上面, exists_callback只会被使用一次,所以保存一些代码并将其作为匿名函数传递。 另外,在node.js中,你应该使用camelCase而不是下划线,例如getIndex over return_index

看起来requestpath将uri映射到文件系统 – 但它并不指向特定的文件(例如: http:// localhost / maps to / myrootpath /)。 你想要做的是从该文件夹中提供默认文件(例如:index.html),我认为它存储在options.index中。 这就是为什么你必须追加options.indexpath。