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