I'm trying to connect my Chrome browser on my local machine to my remote node server with socket.io. I'm serving all the files off my node server with expressjs so I have a public directory with the html and js files (I created a symlink to the socket.io files under node_modules I got from npm).
The problem I'm having is that when Chrome pulls my index.html I get the following errors:
Uncaught ReferenceError: require is not defined socket.io.js:12 Uncaught ReferenceError: io is not defined
I tried the cdn like a few other posts but that resulted in another issue. Many posts advocate this approach so I'm not sure why it's not resolving the nodejs stuff. Any ideas?
Here's what my index.html looks like:
<html>
<head>
</head>
<body>
<script src="http://nodeserver:8080/socket.io/lib/socket.io.js"></script>
<script>
var socket = io.connect('http://nodeserver:8080');
socket.on('', function (data) {
console.log(data);
socket.emit('update checkins', { my: 'data' });
});
</script>
<h2>Test Page</h2>
</body>
</html>
My server code looks like this:
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
// Get the environment variables we need.
var ipaddr = process.env.VCAP_APP_HOST || 'myserver.com';
var port = process.env.PORT || 8080;
app.configure(function() {
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
// set up the RESTful API, handler methods are defined in api.js
var api = require('./controller/api.js');
app.get('/foursq', api.list);
// Set Socket.io
io.sockets.on('connection', function (socket) {
console.log('Socket created...');
socket.emit('welcome', {welcome: 'you'});
socket.on('update checkins', function (msg) {
socket.broadcast.emit('checkins', api.list);
});
});
// And start the app on that interface (and port).
app.listen(port, ipaddr, function () {
console.log('%s: Foursquare Node server started on %s:%d ...', Date(Date.now()),
ipaddr, port);
});
The problem is I had the original code listening on the app object, but when I updated the code to add sockets, I neglected to change that as server.listen as follows:
server.listen(port, ipaddr, function () {
console.log('%s: Foursquare Node server started on %s:%d ...', Date(Date.now()),
ipaddr, port);
});
This then allows me to simply put the script includes as following without having to copy anything as billy points out:
<script src="/socket.io/socket.io.js"></script>