为什么 “/” 在节点.js中没有提供索引.html

Why isn't "/" serving index.html in node.js?

本文关键字:html 索引 js 节点 为什么      更新时间:2023-09-26

我正在尝试编写一个返回主页的函数,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正在将/更改为/index.html,没有它fs.exists将找不到文件。(/是一个目录,而不是一个文件,因此是错误的。

这可能看起来令人困惑,因为localhost:3000/应该服务于index.html。在 Web 上,/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);
    });
}

尝试使回调匿名,除非您知道要在其他地方使用它们。上面,exists_callback只会使用一次,因此请保存一些代码并将其作为匿名函数传递。此外,在 node.js 中,您应该使用camelCase而不是下划线,例如,getIndex over return_index

看起来 requestpath 将 uri 映射到文件系统 - 但它没有指向特定的文件(例如:http://localhost/映射到/myrootpath/)。您要做的是提供该文件夹中的默认文件(例如:index.html),我认为该文件存储在options.index中。这就是为什么你必须将 options.index 附加到路径中。