Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么不是';"/&引用;在node.js中提供index.html?_Javascript_Node.js - Fatal编程技术网

Javascript 为什么不是';"/&引用;在node.js中提供index.html?

Javascript 为什么不是';"/&引用;在node.js中提供index.html?,javascript,node.js,Javascript,Node.js,我正在尝试编写一个返回主页面的函数,index.html。但是,当我删除该行时 requestpath += options.index 我得到以下错误: 500: encountered error while processing GET of "/" 如果没有这一行,请求不是应该服务于index.html的localhost:3000/ 我猜它与最后的fs.exist函数有关,但我不确定 var return_index = function (request, response, r

我正在尝试编写一个返回主页面的函数,
index.html
。但是,当我删除该行时

requestpath += options.index
我得到以下错误:

500: encountered error while processing GET of "/"
如果没有这一行,请求不是应该服务于
index.html
localhost:3000/

我猜它与最后的
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);
}
选项
等于

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

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

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\u callback
只会使用一次,所以请保存一些代码并将其作为匿名函数传递。另外,在node.js中,您应该使用
camelCase
而不是下划线,例如
getIndex
over
return\u index

在什么上下文中,这个node.js是什么,以及
requestpath
做什么?看起来区别在于绝对路径和相对路径以及什么是
选项。索引
?你可以
console.log(options.index)并告诉我们它返回了什么?是的,它是node.js。我将用option.index更新帖子