Node.js - 基本 Node Web 服务器未提供 Socket.io 客户端文件

标签 node.js include socket.io

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

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

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

我的理解是 Node 应该选择并解决它?它在一个更简单的 Web 服务器示例上执行。

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

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();
        }
    });

我的 Web 服务器代码解析如下:

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 文件?

最好的问候,本。

最佳答案

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

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

关于Node.js - 基本 Node Web 服务器未提供 Socket.io 客户端文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8459007/

相关文章:

javascript - node.js 强制只有一个线程执行代码

node.js - 防止直接访问 Node & Express 应用程序中的目录

javascript - CoffeeScript 中的客户端依赖管理

c++ - 如何在 Visual Studio 2017 中使用 VC++ 包含目录的子文件夹

php - 如何在 Symfony 中将 php 代码包含到我的 Controller 中?

javascript - 在 c++ 和 node.js(服务器)之间建立套接字通信的困难

Node.js 和 Express 静态中间件路由 View

node.js - 如何用Node.js的fs模块和express实现文件下载

c++ - 为子项目应用 CMake 设置

javascript - Node.js 对象不是函数 - module.exports