uncoded
uncoded

Reputation: 113

CORS Blocked with node.js and socket.io

I recently started learning node.js and socket.io. I followed a simple tutorial that socket.io had and it all worked fine while running on my computer. However, I decided to upload the client part to a server for testing and that is where the problems began. I would like to run the chat client on a web host, and run the server on my computer, or another host. Basically, I plan on port forwarding the server, and having the client run on a web page. I opened my port to port forward and it seems to be working, however I am getting the error on the web page every time.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://24.151.51.34:3000/socket.io/?EIO=3&transport=polling&t=1437399007343-0. (Reason: CORS request failed).

I've been messing around with the code in hopes of finding a solution to this problem before starting my own project, however I can't figure out a way. The client code is :

<!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 the server code I tried to add code to allow CORS but really not 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) {
    // Handle the post for this route
});

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
  });
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

Upvotes: 8

Views: 20931

Answers (4)

Nuwan Kirillawala
Nuwan Kirillawala

Reputation: 11

I found the same problem while my developing. And I found the solution and it works for me

const express = require('express');
const socketio = require('socket.io');
const http = require('http');
const router =  require('./router');
const cors = require('cors');

const PORT = process.env.PORT || 5000;

const app =  express();
const server = http.createServer(app);
const io = socketio(server, { cors: { origin: '*' } });

app.use(cors());

io.on('connection', (socket) => {
    console.log('We have a new connection!!!');

    socket.on('disconnect', () => {
        console.log('User had left!!!');
    })
});

app.use(router);

server.listen(PORT, () => {
    console.log(`Server has started on port: ${PORT}`);
});

also, I want to highlight this line

const io = socketio(server, { cors: { origin: '*' } });

It creates a Socket.IO server instance with CORS (Cross-Origin Resource Sharing) enabled.

Upvotes: 1

tnaluat
tnaluat

Reputation: 126

Besides using cors package, I managed to fix it by adding options to the socketio creation. Starting from the version 3 cors config has changed and you have to add these options. Worked on socket version 2.x.x also.

  const io = socketio(httpServer, {
  cors: {
    origin: "http://localhost:3000",
    methods: ["GET", "POST"],
    credentials: true
  }
});

Here is the resource https://socket.io/docs/v3/handling-cors/

Bonus: In case you encounter Bad Request make sure you have the same version of socket.io for the client and the server.

Upvotes: 11

Aklesh Singh
Aklesh Singh

Reputation: 973

i am using npm cors package now and it work like a charm No problem with socket.io too.

Add it like this app.options('*', cors());

which means Access-Control-Allow-Origin: '*'

var express = require('express');
var app = express();
var http = require('http').Server(app);
const cors = require('cors');
var bodyParser   = require('body-parser');
app.use(cors());
app.options('*', cors());

const auth = require('./routes/auth');

 const port = 3004;
http.listen(port, () => {
  console.log( `running http at port ${port}`);
});

Upvotes: -1

uncoded
uncoded

Reputation: 113

I managed to solve the problem by using this CORS middle ware someone recommended me and checking my firewall settings. https://www.npmjs.com/package/cors

Upvotes: 2

Related Questions