dev333
dev333

Reputation: 799

Getting Cross-Origin Request Blocked Error when trying to run socket.io sample

While running the below socket.io sample,I'm getting the below error in the firebug.Can anyone please help me out regarding this issue ...

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost/socket.io/?EIO=3&transport=polling&t=1447667170745-0. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

My app.js:

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

server.listen(80);

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

My index.html :

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>

Upvotes: 1

Views: 812

Answers (2)

vivek s vamja
vivek s vamja

Reputation: 999

Install cors library in your node js. Command to install cors is as below.

npm install cors

Now add below code to your nodejs server file to allow cross origin request allow.

var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());

Sometime its necessary to keep your nodejs client file in root directory where your index file is.

Just check your firewall setting it also block the server port that you are using.

Hope it's work for you.

Upvotes: 3

Andrius
Andrius

Reputation: 5939

Try changing the server listening port:

server.listen(8080);

Now that we will be using port 8080, change the HTML script to connect to that port:

var socket = io.connect('http://localhost:8080');

It should all work just fine.

Upvotes: 2

Related Questions