[英]Getting a binding error when trying to run Node http server
我們應該創建一個簡單的http節點服務器,該服務器應使用一個名為index.html的文件來響應root-url請求。 不要使用ExpressJS。 代碼應具有錯誤檢查和至少一個回調。 在您的index.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與.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.exists ,該字符串需要一個字符串路徑,並為其提供文件處理程序索引。 這就是為什么錯誤是:
path must be a string
請嘗試使用字符串“ index.html”,而不要在此處同步。 在存在的回調中異步執行嗎
fs.exists("index.htm", function(){ fs.readFile("index.htm")
用'index.html'替換index變量可以完成工作,但是
請不要使用fs.exists,請閱讀其API文檔http://nodejs.org/api/fs.html#fs_fs_exists_path_callback
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.