尝试运行节点 http 服务器时出现绑定错误

Getting a binding error when trying to run Node http server

本文关键字:绑定 错误 服务器 试运行 节点 http      更新时间:2023-09-26

我们应该创建一个简单的http节点服务器,它应该使用一个名为index.html的文件响应root-url请求。不要使用 ExpressJS。代码应具有错误检查和至少一个回调。在索引中放置五个或更多 html 元素.html。其中一个元素应该是指向外部页面的链接。

这是我的代码:

var http = require("http");
var fs   = require('fs');
var index = fs.readFileSync('index.html');

var server = http.createServer(function(request, response) {
fs.exists(index, function(exists) {
     try {
       if(exists) {
  response.writeHead(200, {"Content-Type": "text/html"});
  response.write("<html>");
  response.write("<head>");
  response.write("<title>Hello World!</title>");
  response.write("</head>");
  response.write("<body>");
  response.write("<div>");
  response.write("Hello World!");
  response.write("</div>");
  response.write("<a href='http://www.google.com' target='_blank'>Google</a>")
  response.write("</body>");
  response.write("</html>");
        } else {
         response.writeHead(500);
        }
    } finally {
         response.end(index);
    }
 });
});
 
server.listen(80);
console.log("Server is listening");

我收到此绑定错误:

服务器正在侦听

fs.js:166
  binding.stat(pathModule._makeLong(path), cb);
          ^
TypeError: path must be a string
    at Object.fs.exists (fs.js:166:11)
    at Server.<anonymous> (/Users/rahulsharma/Desktop/server.js:8:4)
    at Server.emit (events.js:98:17)
    at HTTPParser.parser.onIncoming (http.js:2112:12)
    at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:121:23)
    at Socket.socket.ondata (http.js:1970:22)
    at TCP.onread (net.js:527:27)

有什么想法吗?

用"index.html"替换索引变量可以完成这项工作,但

请不要使用 fs.exist,阅读其 API 文档http://nodejs.org/api/fs.html#fs_fs_exists_path_callback

将索引.html与.js文件放在一起。将所有 html 放在该文件中。

var http = require("http");
var fs   = require('fs');
var server = http.createServer(function(req, res) {
    fs.readFile("index.html",function(err,content){
        if(err){
            throw err;
            console.log("Error reading index file.");
            res.send("Aw snap!");
        }
        else{
            res.writeHead(200,{"Content-type":"text/HTML"});
            res.end(content,"UTF-8");
        }
    });
});
server.listen(80);

根据堆栈跟踪,错误位于以下行中:

fs.exists(index, function(exists)

您传递给此函数(检查给定文件是否存在)实际上是文件的内容。您应该作为第一个参数传递的内容可能是"index.html"而不是index变量

您正在尝试调用 fs.exist,它需要一个字符串路径,并且您正在为其提供文件处理程序索引。这就是为什么错误是:

path must be a string

要么尝试使用字符串"index.html",并且不要在那里同步读取它。在现有回调中异步执行

fs.exists("index.htm", function(){ fs.readFile("index.htm")