我们应该创建一个简单的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)
有什么想法吗?
答案 0 :(得分:0)
将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);
答案 1 :(得分:0)
根据您的堆栈跟踪,错误在此行内:
fs.exists(index, function(exists)
传递给此函数的内容(检查给定文件是否存在)实际上是文件的内容。作为第一个参数,您应该传递的内容可能是"index.html"
而不是index
变量
答案 2 :(得分:0)
您正在尝试调用期望字符串路径的fs.exists,并且您正在为其提供文件处理程序索引。 这就是错误原因:
path must be a string
尝试使用字符串&#34; index.html&#34;并且不要在那里同步阅读它。在exists回调
中执行异步fs.exists("index.htm", function(){ fs.readFile("index.htm")
答案 3 :(得分:0)
用&#39; index.html&#39;替换索引变量会做的但是
请不要使用fs.exists,阅读其API文档 http://nodejs.org/api/fs.html#fs_fs_exists_path_callback