Patryk
Patryk

Reputation: 24092

Why I get 'Cannot GET /' on my express server?

I wrote a minimalistic example of a server with node.js with which I want to get console notification that client connected. I am using following version of modules

So I wrote this :

app.js

var socket = require('socket.io');
var express = require('express');
var http = require('http');

var app = express();

var server = http.createServer(app);

var io = socket.listen(server);
//var io = socket.listen(app);

io.sockets.on('connection',function(client){
        console.log("Client connected...");

        client.emit('messages', {hello: 'world'});
});

app.listen(8080);

index.html

<script src="node_modules/socket.io/lib/socket.io.js"></script>
<script>
    var server = io.connect("http://localhost:8080");

    server.on('messages', function(data){
        alert(data.hello);
    });

</script>

I have my catalog structure as follows:

|-- app.js
|-- index.html
`-- node_modules
    |-- express
    |   |-- bin
    |   |-- client.js
    |   |-- History.md
    |   |-- index.js
    |   |-- lib
    |   |-- LICENSE
    |   |-- Makefile
    |   |-- node_modules
    |   |-- package.json
    |   |-- Readme.md
    |   `-- test.js
    `-- socket.io
        |-- benchmarks
        |-- History.md
        |-- index.js
        |-- lib
        |-- LICENSE
        |-- Makefile
        |-- node_modules
        |-- package.json
        `-- Readme.md

Upvotes: 3

Views: 16492

Answers (1)

Ivan Drinchev
Ivan Drinchev

Reputation: 19581

Your line :

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

should be replaced with

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

By doing this you are serving the static socket.io.js module for the client directly through socket.io's internal static server and not by ExpressJS itself!

EDIT 1 :

Oh and I forgot to mention how to serve your index.html file so basically you need to set

var app = express();

app.use(express.static(__dirname + '/public'));

and then place your index.html file in your /public directory

EDIT 2 : ( explaination )

ExpressJS serves static files through internal static file handler. The line app.use(express.static(__dirname + '/public')); actually reroutes your requests passed to node.js to your public folder.

Socket.io on the other hand ( as a separate library ) has it's own method to serve it's static files and it is triggered only with GET request that contains URL : /socket.io/socket.io.js ( although there is another flash file .swf that is served for browsers that doesn't support Websockets )

You can learn more from the ExpressJS API and Socket.io wiki.

Upvotes: 9

Related Questions