我是新來的Node.js,我試圖在server1.js文件中配置我的路由。需要幫助使用socket.io路由
當我去我的localhost:3000/socket.html
它不讀socket.html
的情況,而是直接進入默認情況。
但是當我輸出的控制檯日誌。我看到的路徑是否正確輸出是/socket.html
,我真搞不明白爲什麼它不達到這個case語句的路徑。
任何幫助將非常感激。以下是我正在使用的代碼。
var http = require('http');
var url = require('url');
var fs = require('fs');
var server = http.createServer(function(request,response){
console.log('Connection');
var path = url.parse(request.url).pathname;
console.log(path); //Shows the correct path in console
switch(path){
//This case statement works
case '/':
response.writeHead(200,{'Content-Type': 'text/html'});
response.write('hello world');
break;
//It doesn't reach this case statement
case 'socket.html':
fs.readFile(__dirname + path, function(error,data) {
if(error){
response.writeHead(404);
resonse.write("oops this file doesn't exist - 404");
} else {
response.writeHead(200, {"Content-Type" : "text/html"});
response.write(data,"utf8");
}
});
console.log('socket path');
break;
default :
response.writeHead(404);
response.write("oops this doesn't exist - 404 coming from deafult");
break;
}
response.end();
});
server.listen(3000);
難道是因爲'/ socket.html'不等於'socket.html'嗎? – bloodyKnuckles
@bloodyKnuckles我試過使用/socket.html,但它只是顯示一個空白頁面,沒有任何內容 – json2021