0

This is my server.py file. I have used socketio to be called from react application.

async_mode = None
app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = 'nuttertools'
Session(app)
CORS(app)
cors = CORS(app, resources={r"*": {"origins": "*"}})

# socketio = SocketIO(app, manage_session=False, async_mode=async_mode)
socketio = SocketIO(app, manage_session=False, async_mode=async_mode, cors_allowed_origins='*')

@socketio.on('message', namespace='/chat')
def chat_message(message):
    print("message =!! ", message)
    test_message = message
    print("test message ", test_message)

    emit('message', {'data': test_message['data']}, broadcast=False)

if __name__ == '__main__':
    socketio.run(app, host=host, port=port, debug=True)

But when I am calling this socketio from react application, I am getting the following error.

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

My react code is as following:

const serverHost = window.location.hostname;
const serverPort = 5003;
const serverUrl = `http://${serverHost}:${serverPort}/chat`;
console.log(serverUrl);

class App extends Component {
    constructor(props) {
        super(props);
        // this.completeChange = this.completeChange.bind(this);
        this.state = {
            userMessage: '',
            conversation: [{
                text: "Please enter your mobile number",
                user: 'ai',
            }],
            socket: io(serverUrl),
            childVisible: false,
            show: false,
            selectedValue: undefined,
            radioOptions: [],
            headerControler: false,
            mobileNoTaken: false
        };
    }

How can I solve the corse origin policy error?

A Stranger
  • 1,816
  • 2
  • 24
  • 58

1 Answers1

0

Cors error can be handle like

const io = require("socket.io")(httpServer, {
  origins: ["https://example.com"],

  // optional, useful for custom headers
  handlePreflightRequest: (req, res) => {
    res.writeHead(200, {
      "Access-Control-Allow-Origin": "https://example.com",
      "Access-Control-Allow-Methods": "GET,POST",
      "Access-Control-Allow-Headers": "my-custom-header",
      "Access-Control-Allow-Credentials": true
    });
    res.end();
  }
});

Refer :Socket-cors-handling

Shahnad
  • 129
  • 9