簡體   English   中英

為什么“ /”在node.js中不提供index.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 在網絡上, /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

看起來requestpath映射uri到文件系統-但它沒有指向特定文件(例如: http:// localhost /映射到/ myrootpath /)。 您要做的是從該文件夾提供默認文件(例如:index.html),我認為該文件存儲在options.index中。 這就是為什么您必須在路徑中附加options.index的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM