How set socket.io CORS for heroku?

Viewed 1093

How to set CORS for heroku if I using socket.io with Express? My app works on localhost but when I deploy on Heroku it is not working on mobile phone and on Chrome. When I check the console.log on chrome I get this error.

A`ccess to XMLHttpRequest at 'https://fart-game.herokuapp.com/socket.io/?EIO=4&transport=polling&t=Nc0YKct' from origin 'http://fart-game.herokuapp.com' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains the invalid value 'https://fart-game.herokuapp.com/'.`

My index.js looks like this

const express = require('express');
const path = require('path');
const http = require('http');
const socketio = require('socket.io');

const { addUser, getUser, getUsersInRoom, removeUser } = require('./users');
const { rollFunction, 
        sumNumbers
    } = require('./game')

var cors = require('cors');

const app = express();
app.use(cors())

const buildPath = path.join(__dirname, '..', 'build');
 app.use(express.static(buildPath));

const server = http.createServer(app);

const io = socketio(server, {
    cors: {
        origin: `https://fart-game.herokuapp.com/`,
        methods: ["GET", "POST"],
        credentials: true
      }
});

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

const router = require('./router');
const { get } = require('./router');
const { isFunction } = require('util');

app.use(router)

server.listen(PORT, () => {
    console.log(`Server is runing on port ${PORT}`);
});

Dependencies

"cors": "^2.8.5",
 "express": "^4.17.1",
 "socket.io": "^4.0.1"
1 Answers

I noticed this part in the error

 from origin 'http://fart-game.herokuapp.com' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains the invalid value 'https://fart-game.herokuapp.com/'.`

You accept cross-origin requests from https://fart-game.herokuapp.com/ but actually send requests from http://fart-game.herokuapp.com, so it doesn't work.

I think this should work :

const io = socketio(server, {
    cors: {
        origin: `http://fart-game.herokuapp.com`, // I copied the origin in the error message and pasted here
        methods: ["GET", "POST"],
        credentials: true
      }
});
Related