I recently started learning node.js and socket.io. I followed a simple tutorial that socket.io had and it all worked fine while working on my computer. However, I decided to upload the client part to the server for testing, and it was there that the problems started. I would like to start the chat client on the website and start the server on my computer or another host. Basically, I plan on port forwarding to the server, and the client works on the web page. I opened the port for the port and it seems to work, however every time I get an error on the web page.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http:
I already fiddled with the code in the hope of finding a solution to this problem before starting my own project, however I cannot figure out a way. Client code:
<!doctype html> <html> <head> <title>Socket.IO chat</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font: 13px Helvetica, Arial; } form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; } form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; } form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; } #messages { list-style-type: none; margin: 0; padding: 0; } #messages li { padding: 5px 10px; } #messages li:nth-child(odd) { background: #eee; } </style> </head> <body> <ul id="messages"></ul> <form action=""> <input id="m" autocomplete="off" /><button>Send</button> </form> <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script> <script src="http://code.jquery.com/jquery-1.11.1.js"></script> <script> var socket = io('24.151.51.34:3000'); $('form').submit(function(){ socket.emit('chat message', $('#m').val()); $('#m').val(''); return false; }); socket.on('chat message', function(msg){ $('#messages').append($('<li>').text(msg)); }); </script> </body> </html>
For server code, I tried adding code to enable CORS, but I'm not really sure what to do:
var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); io.set('origins', 'http://browsercombat.com:80'); app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); res.header("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS"); res.header("Access-Control-Allow-Credentials", "true"); next(); }); app.get('/', function(req, res, next) { res.sendFile(__dirname + '/index.html'); }); app.post('/', function(req, res, next) {