这是我的代码。
var server = http.createServer(function(request, response){
console.log('Connection');
var path = url.parse(request.url).pathname;
path = path.substr(1);
switch(path){
case '':
response.writeHead(200, {'Content-Type':'text/html'});
response.end();
break;
case 'socket.html':
response.write("read file"); //works
fs.readFile(__dirname + '\\' + path, function(error, data){
if (error){
response.writeHead(404); //this doesn't work
}
else{
response.writeHead(200, {'Content-Type':'text/html'}); //doesn't work
response.write("OK"); //doesn't work
}
});
response.end();
break;
default:
response.writeHead(404);
response.end();
break;
}
});
服务器侦听端口 8001,当我访问http://myhost.com:8001/socket.html时,我只能看到“读取文件”。响应的方法似乎在回调函数 readFile 中损坏了。有人可以告诉我为什么并给我一个解决方案吗?谢谢!(原谅我糟糕的英语:))。