I have a website at a url (example.com) and am using node.js/socket.io to pass JSON into my webpage. I'm currently receiving an error: "XMLHttpRequest cannot load http://example.com:12003/socket.io/1//897026922693503087/?disconnect=1. Origin http://example.com is not allowed by Access-Control-Allow-Origin."
My node code looks like the following:
var http = require('http');
var mysqlClient = require('mysql').createClient({'user':'root','password':'XXXXXXXX'});
mysqlClient.query('USE myDBName');
var mysqlData;
setInterval(function(){
mysqlClient.query(
'SELECT number, page_id FROM dbTableName',
function selectCb(err, results, fields) {
if (err) {
throw err;
}
mysqlData = [];
for(var i = 0; i < results.length; i++){
mysqlData[i] = results[i];
}
});
}, 1000);
var io = require('socket.io').listen(12003);
io.sockets.on('connection', function(client) {
console.log("New Connection: ", client.id); //log new connection
client.emit('connection', client.id);//custom emit to let site know its connected
client.on("requestNewData", function(data){
client.emit('init', JSON.stringify(mysqlData));
});
client.on('disconnect', function() {
console.log("Disconnected: ", client.id);
});
});
I've tried this line of code to fix the issue with no success:
var io = require('socket.io').listen(12003, {origins: '*:*'});
I'm running on an Amazon EC2 with Ubuntu Ocelot. My client side code is:
<script src="http://example.com:12003/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect('http://example.com:12003');
socket.emit("requestNewData", {"nothing":"here"});
...
Since I'm just using a socket I don't think I can use 'Access-Control-Allow-Origin' : '*' in my node code. Any help would be greatly appreciated. The error I'm receiving is only on Chrome - from my understanding Chrome is more restrictive about cross-domain connections...
Thanks in advance.
Try just including the relative path for your socket.io on the client:
<script src="/socket.io/socket.io.js"></script>
var socket = io.connect('http://example.com');