2017-05-03 5 views
0

node.jsに新しいが、以下のリンクで基本的なチュートリアルに従っていました。 https://www.tutorialspoint.com/nodejs/nodejs_web_module.htmNode.JS hosting basic webpageエラー: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に指定されたURLを使用している://127.0.0.1:8081/index.htm'?特に '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