繁体   English   中英

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

[英]Why isn't “/” serving index.html in node.js?

我正在尝试编写一个返回主页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 在网络上, /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超过return_index

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM