简体   繁体   English

Node.js - Socket.io客户端文件不由基本节点Web服务器提供

[英]Node.js - Socket.io client file not being served by basic node web server

I m very new to Node.js and Socket.io. 我是Node.js和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). 我已经构建了一个非常基本的Web服务器,但是在使用它时,我无法加载socket.io客户端文件(我得到了404)。

I am trying to use this client side code: 我正在尝试使用此客户端代码:

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

My understanding is that Node should pick this up and resolve it? 我的理解是Node应该选择并解决它? It does on a much simpler web server example. 它在一个更简单的Web服务器示例上。

My web server example where it is NOT resolved is as follows: 我的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();
        }
    });

My web server code where it DOES resolve is as follows: 我解决的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);
  });
}

Can anyone advise on what is causing it not serve the socket.io file on the client using the first web server example? 任何人都可以建议使用第一个Web服务器示例在客户端上不提供socket.io文件的原因是什么?

Best regards, Ben. 此致,本。

You are probably running Socket.IO on a different port, so include the file in the following format: 您可能在另一个端口上运行Socket.IO,因此请按以下格式包含该文件:

server:port/socket.io/socket.io.js 服务器:端口/ socket.io / socket.io.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM