4

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>

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

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

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

Best regards, Ben.

1
  • where is your socket.io code? Commented Dec 10, 2011 at 19:11

1 Answer 1

11

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

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the prompt reply. I am running the web server on 8080. Will socket.io not be on the same port?
Is Socket.IO on the same port? Are you sure?
Thats it! It was running on 8080 in the first example. Many thanks! Ben.
I ran into the same problem. Thank you for posting the answer. Everything is complicated when you're a noob :)
@alessioalex Where I need to provide thr fix
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.