我正在尝试编写一个返回主页的函数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
over return_index
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句