【问题标题】:Node.js / Express / Socket.io Not working on Localhost but works by going direct fileNode.js / Express / Socket.io 不在本地主机上工作,但通过直接文件工作
【发布时间】:2012-11-16 15:47:32
【问题描述】:

我正在开发一个多人 HTML5 游戏,使用 Node.js 作为 Express 服务器,使用 Socket.io 作为 websockets。当我尝试在浏览器中访问应用程序正在侦听的端口中的游戏时,我得到一个空白页面。但是,当我直接访问 index.html 文件时(在服务器运行时),它可以完美运行。

注意,当我说“直接访问文件”时,我的意思是:file:///C:/Program%20Files/nodejs/SupermarketChallenge/public/index.html

这很好,直到我想和我的室友一起测试游戏,他需要通过 localhost 访问它才能玩!

这是相关的服务器代码:

var express = require('express'),
    //Create an express server
    app = express.createServer(),
    //attach socket.io to the server
    supermarket = require('socket.io').listen(app);

//Configure a static directory for public files
app.configure(function() {
    app.use(express.static(__dirname + '/public'));
});

//set the port to listen to
app.listen(3000);

还有客户:

var socket = io.connect('http://localhost:3000'); 

【问题讨论】:

    标签: node.js express socket.io localhost


    【解决方案1】:

    这是因为转到http://localhost:3000/ 与您的公共文件夹中的任何有效文件都不匹配。你需要一条路线来匹配这个。根据以下内容更新您的代码:

    var express = require('express'),
        //Create an express server
        app = express.createServer(),
        //attach socket.io to the server
        supermarket = require('socket.io').listen(app);
    
    //Routes
    app.get('/', function(req, res) {
        res.redirect('/index.html');
    });
    
    //Configure a static directory for public files
    app.configure(function() {
        app.use(app.router);
        app.use(express.static(__dirname + '/public'));
    });
    
    //set the port to listen to
    app.listen(3000);
    

    现在可以更改您的路由以实际提供index.html 的内容,在这种情况下,您可以将/ 路由替换为以下内容:

    //Routes
    app.get('/', function(req, res) {
        res.sendfile(__dirname + '/public/index.html');
    });
    

    【讨论】:

    • 感谢您的回复!这并没有解决它,但我认为这可能是由于我的措辞模棱两可。如果我在 localhost:3000/index.html 访问该文件,它将不起作用。当我通过文件系统访问文件时,例如file:///C:/Program%20Files/nodejs/SupermarketChallenge/public/index.html 然后它确实有效。另外,我有一个
      用于一些调试输出文本。这确实使用 localhost 加载,但画布完全是空白的。
    • 嗯,这似乎是一个与服务器无关的问题,更多的是您的客户端脚本指向的位置,就路径而言。我建议在 chrome 中进行一些调试,以查看 Websocket 是否正在连接。默认情况下,服务器上的 socket.io 应该将调试级别的消息输出到控制台。确保您的观看活动。除此之外,发布更多的客户端脚本可能会有所帮助。
    【解决方案2】:
    const app = require("express")();
    const httpServer = require("http").createServer(app);
    const options = { /* ... */ };
    const io = require("socket.io")(httpServer, options);
    
    io.on("connection", socket => { /* ... */ });
    
    httpServer.listen(3000);
    // WARNING !!! app.listen(3000); will not work here, as it creates a new HTTP server
    

    【讨论】:

    • 你能解释一下代码在做什么吗?
    • 其实 express 是做一个服务器,然后把那个服务器交给 httpServer,所以我们必须使用 httpServer.listen 而不是 app.listen
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签