需要帮助使用socket.io路由

问题描述:

我是新来的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); 
+1

难道是因为'/ socket.html'不等于'socket.html'吗? – bloodyKnuckles

+0

@bloodyKnuckles我试过使用/socket.html,但它只是显示一个空白页面,没有任何内容 – json2021

您有两个问题。首先是路径不匹配 - 它是/socket.html,而不是socket.html,所以这就是你必须放在你的case

其次,您在switch声明后立即致电response.end(),但/socket.html大小写是异步的,因此尚未完成此操作。您应该在每个case中分别拨打response.end(),以便完成异步操作。

+0

非常感谢Ahron。这正是问题所在! – json2021