Node.JS hosting basic webpage Error: ENOENT

Node.JS hosting basic webpage Error: ENOENT

node.js 的新手,正在学习下方 link 中的基本教程。 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/');

创建了 2 个文件 index.html 和 server.js 与 post 完全相同。 然后当我尝试 运行 它与

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: '' }

在给定的代码中你有:

// 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.