2017-05-03 134 views
0

新增至node.js並且正在遵循下面鏈接中的基本教程。 https://www.tutorialspoint.com/nodejs/nodejs_web_module.htmNode.JS託管基本網頁錯誤:ENOENT

var http = require('http'); 
var fs = require('fs'); 
var url = require('url'); 

// Create a server 
http.createServer(function (request, response) { 
    // Parse the request containing file name 
    var pathname = url.parse(request.url).pathname; 

    // Print the name of the file for which request is made. 
    console.log("Request for " + pathname + " received."); 

    // Read the requested file content from file system 
    fs.readFile(pathname.substr(1), function (err, data) { 
     if (err) { 
     console.log(err); 
     // HTTP Status: 404 : NOT FOUND 
     // Content Type: text/plain 
     response.writeHead(404, {'Content-Type': 'text/html'}); 
     }else { 
     //Page found  
     // HTTP Status: 200 : OK 
     // Content Type: text/plain 
     response.writeHead(200, {'Content-Type': 'text/html'});  

     // Write the content of the file to response body 
     response.write(data.toString());  
     } 
     // Send the response body 
     response.end(); 
    }); 
}).listen(8081); 

// Console will print the message 
console.log('Server running at http://127.0.0.1:8081/'); 

創建2個文件中的index.html和server.js完全相同的訊息。 後來,當我嘗試與

node server.js

沒有錯誤消息顯示了運行它,但是當我試圖訪問我的瀏覽器的頁面不連接並在控制檯中的錯誤出現。

任何幫助將不勝感激。

Server running at http://127.0.0.1:8081/

Request for/received.

{ Error: ENOENT: no such file or directory, open '' errno: -2, code: 'ENOENT', syscall: 'open', path: '' }

+1

您是否使用了教程'http://127.0.0.1:8081/index.htm'中指定的url?特別是最後的'index.htm'部分。 – Sirko

+0

你必須在你的問題中包含相關的代碼,而不是鏈接到外國網站。 –

回答

4

在給定的代碼,您有:

// Print the name of the file for which request is made. 
console.log("Request for " + pathname + " received."); 

// Read the requested file content from file system 
fs.readFile(pathname.substr(1), function (err, data) { 

因爲路徑是/pathname.substr(1)將導致一個空字符串。並且由於您沒有沒有名稱的文件,因此fs.readFile找不到要讀取的文件,這會導致ENOENT錯誤。

給定的代碼不會自動將空字符串解釋爲index.html

所以你必須在瀏覽器中使用http://127.0.0.1:8081/index.html。或者改變代碼的邏輯來解釋空字符串爲index.html

+0

這非常有道理。我認爲它只需要我的本地主機和端口號來訪問託管頁面。最後沒有放入index.html。這也回答了我爲什麼我從來沒有看到索引文件的引用。 – Eric