为什么 “/” 在节点.js中没有提供索引.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
。在 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_callback
只会使用一次,因此请保存一些代码并将其作为匿名函数传递。此外,在 node.js 中,您应该使用camelCase
而不是下划线,例如,getIndex
over return_index
。
看起来 requestpath 将 uri 映射到文件系统 - 但它没有指向特定的文件(例如:http://localhost/映射到/myrootpath/)。您要做的是提供该文件夹中的默认文件(例如:index.html),我认为该文件存储在options.index中。这就是为什么你必须将 options.index 附加到路径中。
- 在索引.html和应用.js [node.js] 之间共享变量
- 限制对HTML/CSS/IMG或根索引文件夹的访问
- D3选择html——传递函数时,索引从1开始,而不是从0开始
- Disqus的计数.js脚本在索引中无法正常运行.html与react.js网站
- 如何设置元素的z索引?JQuery、Javascript、CSS、HTML
- 使url匹配'/''/索引'和'/index.html'到单一状态
- 将HTML输入到包含的索引页中
- html元素是'由于父级的z索引为负,t注册js点击
- 将JSON从索引操作服务到公用文件夹中的index.html
- 节点.js socket.io 网络服务器提供索引.html以外的其他文件
- 为什么 “/” 在节点.js中没有提供索引.html
- 同时使用索引.html和索引.php时,从 URL 中隐藏索引.php
- 如何删除索引中加载的脚本文件中的重复项.html和业力
- Jquery 复制了具有特定索引的 html 类,无法识别点击事件
- 如何观察聚合物元素属性值从索引.html的变化
- 如何将此功能实现到我的索引.html
- 如何打开另一个文件索引.html,具体取决于屏幕的宽度
- 当 Angular 索引页面加载到 DOM [Angular 模板到静态 HTML] 中时,我可以拍摄它的纯 HTML
- 第三方(随机网站访问者)是否有可能通过 php 表单更新.html索引文件中的某些.js代码
- 如何在 html 索引中引用两个使用 jquery 的 HTML 文件