I'm developing a multi-player HTML5 game using Node.js for an Express server and Socket.io for websockets. When I try to access the game in my browser going to the port the application is listening to, I get a blank page. However, when I access the index.html file directly (while the server is running), it works perfectly.
Note, when I say "access the file directly" I mean: file:///C:/Program%20Files/nodejs/SupermarketChallenge/public/index.html
This was fine until I wanted to test the game with my housemate who needs to access it through localhost in order to play!
Here's the relevant server code:
var express = require('express'),
//Create an express server
app = express.createServer(),
//attach socket.io to the server
supermarket = require('socket.io').listen(app);
//Configure a static directory for public files
app.configure(function() {
app.use(express.static(__dirname + '/public'));
});
//set the port to listen to
app.listen(3000);
And the client:
var socket = io.connect('http://localhost:3000');
It's because going to http://localhost:3000/
does not match any valid files from your public folder. You need a route to match this. Update your code according:
var express = require('express'),
//Create an express server
app = express.createServer(),
//attach socket.io to the server
supermarket = require('socket.io').listen(app);
//Routes
app.get('/', function(req, res) {
res.redirect('/index.html');
});
//Configure a static directory for public files
app.configure(function() {
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
//set the port to listen to
app.listen(3000);
Now your route can be altered to actually serve the content of the index.html
, in which case you would replace the /
route with the following:
//Routes
app.get('/', function(req, res) {
res.sendfile(__dirname + '/public/index.html');
});