Monday 12 June 2017

React + Express + Socket.io trouble: "No 'Access-Control-Allow-Origin' header is present on the requested resource."

So I used create-react-app to bootstrap my react project, then I added a small express server. The react app is running on port 3000 and the express app is running on 3001. Thus I set up my socket.io client like this (to be able to listen to the server):const socket = io.connect("http://localhost:3001"); class App extends Component { componentDidMount() { fetch('/api') .then(res => console.log(JSON.stringify(res.json))); socket.on('server-connect', function (data) { console.log('SHOULD RECEIVE A SERVER EVENT:'); console.log(data); socket.emit('client-connect', { connectedToClient: 'true' }); }); }However when it tries to receive data, I get this error: "XMLHttpRequest cannot load http://localhost:3001/socket.io/?EIO=3&transport=polling&t=LoT-cfW. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 404."So then I went into my app and added this, but nothing is working still:app.use(function (req, res, next) { const origin = req.get('origin'); res.header('Access-Control-Allow-Origin', origin); res.header('Access-Control-Allow-Credentials', true); res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control, Pragma'); // intercept OPTIONS method if (req.method === 'OPTIONS') { res.sendStatus(204); } else { console.log(origin); next(); } } );No clue what to do.

Submitted June 12, 2017 at 09:25PM by tangerto

No comments:

Post a Comment