Node.JS托管基本网页错误:ENOENT

Eri*_*ric 0 javascript node.js enoent

node.js的新手,并在下面的链接中遵循基本教程. https://www.tutorialspoint.com/nodejs/nodejs_web_module.htm

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/');
Run Code Online (Sandbox Code Playgroud)

创建了2个文件index.html和server.js完全相同的帖子.然后,当我尝试运行它

node server.js

没有出现错误消息,但是当我尝试访问浏览器上的页面时,它没有连接,并且控制台中显示错误.

任何帮助将受到高度赞赏.

运行于http://127.0.0.1:8081/的服务器

请求/收到.

{错误:ENOENT:没有这样的文件或目录,打开''errno:-2,代码:'ENOENT',系统调用:'打开',路径:''}

t.n*_*ese 5

在给定的代码中,您有:

// 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) {
Run Code Online (Sandbox Code Playgroud)

由于路径/pathname.substr(1)会导致一个空字符串.并且因为您没有没有名称的文件,fs.readFile所以找不到要读取的文件会导致ENOENT错误.

给定的代码不会自动将空字符串解释为index.html.

所以你要么必须http://127.0.0.1:8081/index.html在浏览器中使用.或者更改代码的逻辑以将空字符串解释为index.html.