gpt4 book ai didi

javascript - 为什么 "/"不在 Node.js 中提供 index.html?

转载 作者:太空宇宙 更新时间:2023-11-04 00:58:37 24 4
gpt4 key购买 nike

我正在尝试编写一个返回主页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);
}

选项等于

{
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

关于javascript - 为什么 "/"不在 Node.js 中提供 index.html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28255796/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com