Node.js - Socket.io 客户端文件不由基本节点 Web 服务器提供服务 [英] Node.js - Socket.io client file not being served by basic node web server

查看:22
本文介绍了Node.js - Socket.io 客户端文件不由基本节点 Web 服务器提供服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Node.js 和 Socket.io 非常陌生.我已经构建了一个非常基本的 Web 服务器,但是在使用它时,我无法加载 socket.io 客户端文件(我收到 404).

I m very new to Node.js and Socket.io. I have built a very basic web server however when using it, I am unable to load the socket.io client file (I get a 404).

我正在尝试使用此客户端代码:

I am trying to use this client side code:

<script src="/socket.io/socket.io.js"></script>

我的理解是 Node 应该接收并解决它?它是在一个更简单的 Web 服务器示例上实现的.

My understanding is that Node should pick this up and resolve it? It does on a much simpler web server example.

我的未解析的 Web 服务器示例如下:

My web server example where it is NOT resolved is as follows:

var server = http.createServer(function (request, response) {

    console.log('request starting...');

    var filePath = '.' + request.url;
    if (filePath == './')
        filePath = './index.html';

    var extname = path.extname(filePath);
    var contentType = 'text/html';
    switch (extname) {
        case '.js':
            contentType = 'text/javascript';
            break;
        case '.css':
            contentType = 'text/css';
            break;
    }

    path.exists(filePath, function(exists) {

        if (exists) {
            fs.readFile(filePath, function(error, content) {
                if (error) {
                    response.writeHead(500);
                    response.end();
                }
                else {
                    response.writeHead(200, { 'Content-Type': contentType });
                    response.end(content, 'utf-8');
                }
            });
        }
        else {
            response.writeHead(404);
            response.end();
        }
    });

它解析的我的网络服务器代码如下:

My web server code where it DOES resolve is as follows:

app.listen(8080);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

任何人都可以使用第一个 Web 服务器示例就导致它无法在客户端上提供 socket.io 文件的原因提出建议吗?

Can anyone advise on what is causing it not serve the socket.io file on the client using the first web server example?

最好的问候,本.

推荐答案

您可能在不同的端口上运行 Socket.IO,因此请按以下格式包含该文件:

You are probably running Socket.IO on a different port, so include the file in the following format:

server:port/socket.io/socket.io.js

server:port/socket.io/socket.io.js

这篇关于Node.js - Socket.io 客户端文件不由基本节点 Web 服务器提供服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆