0
votes

I have created a simple app with nodejs to test socketIO, I have run the server on a sub-domain on my website and the client (In ReactJS) is on another sub-domain.

My server always send me the famous error:

Access to XMLHttpRequest at 'https:///socket.io/?EIO=3&transport=polling&t=MyFav6q' from origin 'https://' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I have try than 10 solutions but they don't work, I don't know what's the problem here.

app.js

const cors = require("cors");
const app = require("express")();
app.use(cors());
const server = require('http').createServer(app);
const io = require('socket.io').listen(server);

io.sockets.on('connection', function (socket) {
    socket.emit('message', 'Vous êtes bien connecté !');

    socket.on('message', function (message) {
        console.log(socket.pseudo + ' me dit: ' + message);
        socket.broadcast.emit('message', socket.pseudo + " dit: "+message);
    });

    socket.on("pseudo", pseudo => {
        socket.pseudo = pseudo;
        socket.broadcast.emit('message', socket.pseudo + " s'est connecté !");
    });

    socket.on("reset-draw", data => {
        socket.broadcast.emit('reset-draw', socket.pseudo + " a reset le dessin !");
    });

    socket.on("draw-rect", data => {
        console.log(data);
        socket.broadcast.emit('draw-rect', data);
    });
});

server.listen(8100);

Client on socketIO part:

import socketIOClient from "socket.io-client";

[...]

componentDidMount() {
        this._context = this.refs.canvas.getContext('2d');

        const socket = socketIOClient("https://<ServerURL>");
        socket.emit('pseudo', "testing_guy");
        socket.on("reset-draw", data => {
            this._context.clearRect(0, 0, 500, 500);
            console.log(data);
        });

        socket.on("draw-rect", data => {
            this.drawRect(data);
        });
    }
2
You can configure the cors() middleware for your use-case. - Emile Bergeron
I have already try to add the cors module - Tryliom
It's probably because you're not configuring it correctly for your environment. e.g. cors({credentials: true, origin: true}) - Emile Bergeron

2 Answers

0
votes

Set origins property to io on the server.

io.origins('*')

By default in any case, anything is allowed:

Sets the allowed origins value. Defaults to any origins being allowed. If no arguments are supplied this method returns the current value.

You can also passo a validation function

0
votes

I need to use the IP and port send by my host server and after that I have tried a lot of things but it has only work one day after.