2017-05-03 130 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