1

I'm new to socket.io. I have following code in my NodeJs/Express server

const http = require('http');
const socketIo = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);

io.on('connection', socket => {
    console.log('New client connected');
    socket.on('disconnect', () => console.log('Client disconnected'));
    socket.emit('FromAPI', 'hello');
});
//My port here is 8848
app.listen(app.get('port'), () => {
    logger.log('info', `Server started at :${app.get('port')}`);
});

And following code in Client React app and my react app is hosted in port 3000 as http://localhost:3000

import socketIO from 'socket.io-client';
componentDidMount() {
    const endPoint = 'http://127.0.0.1:8848';
    const socket = socketIO(endPoint);
    socket.on('FromAPI', data => console.log(data));

  }

With this code i got the following error on the browser console:

polling-xhr.js:263 GET http://127.0.0.1:8848/socket.io/?EIO=3&transport=polling&t=MMT-4kl 405 (Method Not Allowed) Failed to load http://127.0.0.1:8848/socket.io/?EIO=3&transport=polling&t=MMT-Aso: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:3000' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

Anyone please help me with this problem.

Zuha Karim
  • 249
  • 4
  • 13
Akas
  • 107
  • 5
  • 11
  • Do you have a CORS extension in your browser. If yes turn that on. If not use this chrome extension and try. [https://chrome.google.com/webstore/detail/moesif-origin-cors-change/digfbfaphojjndkpccljibejjbppifbc?hl=en] – anjuc Sep 03 '18 at 06:33
  • 1
    you need to respond with the correct (calling) host as the value of `access-control-allow-origin` - though to be honest, I can't see where your CORS headers are being sent from anyway – Jaromanda X Sep 03 '18 at 06:33
  • @anjuc - that is extremely poor and dangerous advice – Jaromanda X Sep 03 '18 at 06:34

1 Answers1

1

According to MDN Web Doc , you can add the host urls.

solution 1

There is probably similar question answered already. If that does not work for you try solution 2.

Here is the stackoverflow answer : Solution 1

Solution 2

Limiting the possible Access-Control-Allow-Origin values to a set of allowed origins requires code on the server side to check the value of the Origin request header, compare that to a list of allowed origins, and then if the Origin value is in the list, to set the Access-Control-Allow-Origin value to the same value as the Origin value.

Access-Control-Allow-Origin: https://abc.xyz.gi

so in your case

Access-Control-Allow-Origin: https://localhost

or

Access-Control-Allow-Origin: https://127.0.0.1

Further relevant QA read more on stackeoverflow