Connecting client to server using


I'm relatively new to node.js and it's addons, so this is probably a beginnersquestion.

I'm trying to get a simple HTML page on a webserver connect to a different server running node.js with

My code looks like this:


<script src=""></script>
    // Create SocketIO instance, connect

    var socket = new io.Socket();


    // Add a connect listener
    socket.on('connect',function() {
      console.log('Client has connected to the server!');
    // Add a connect listener
    socket.on('message',function(data) {
      console.log('Received a message from the server!',data);
    // Add a disconnect listener
    socket.on('disconnect',function() {
      console.log('The client has disconnected!');

    // Sends a message to the server via sockets
    function sendMessageToServer(message) {


// Require HTTP module (to start server) and Socket.IO
var http = require('http');
var io = require('');
var port = 8080;

// Start the server at port 8080
var server = http.createServer(function(req, res){ 
    // Send HTML headers and message
    res.writeHead(200,{ 'Content-Type': 'text/html' }); 
    res.end('<h1>Hello Socket Lover!</h1>');


// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);

// Add a connect listener
socket.on('connection', function(client){ 
    console.log('Connection to client established');

    // Success!  Now listen to messages to be received
        console.log('Received message from client!',event);

        console.log('Server has disconnected');

console.log('Server running at' + port + '/');

Starting up the server works fine and running http://localhost:8080 in my browser also works, returning 'Hello Socket Lover' as expected. But I want to make a different page talk to the sockets, not run one from node.js.

But when I run it, nothing happens and the Chrome console returns:

Failed to load resource            http://undefined/
Failed to load resource            http://undefined/

I've been at this all day. Any help?

3/30/2012 3:12:05 PM

Accepted Answer

Have you tried loading the script not from a relative URL?

You're using:

<script src=""></script>



You should try:

<script src="http://localhost:8080/"></script>



Switch localhost:8080 with whatever fits your current setup.

Also, depending on your setup, you may have some issues communicating to the server when loading the client page from a different domain (same-origin policy). This can be overcome in different ways (outside of the scope of this answer, google/SO it).

3/30/2012 3:17:27 PM

You need to make sure that you add forward slash before your link to

<script src="/"></script>

Then in the view/controller just do:

var socket = io.connect()

That should solve your problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow