CORS Policy Error in Flask SocketIO and Angular socket.io-client

124 views Asked by At

I'm trying to learn websocket using Flask and Angular but couldn't solve the CORS problem. Even though I allow CORS, my Angular client websocket cannot connect to Flask server websocket. Below, I added my codes abouts Angular and Flask. Both of them are extremely simple since I'm just trying to establish a connection.

server.py

from flask import Flask
from flask_socketio import SocketIO, send, emit
from flask_cors import CORS, cross_origin 

app = Flask(__name__)

app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, cors_allowed_origins="*")
CORS(app)

@socketio.on('message')
@cross_origin()
def handle_message(data):
    print('received message: ' + data)
    send("test message that should be sent")

if __name__ == '__main__':
    socketio.run(app, host="localhost")

app.component.html

<div *ngFor="let message of messageList">
    <li>
        {{message}}
    </li>
  </div>
  
  <input
    [(ngModel)]="newMessage"
    (keyup)="$event.keyCode == 13 && sendMessage()"
  />
  <button (click)="sendMessage()">Send Message</button>

app.component.ts

import { Component, OnInit } from '@angular/core';
import { WebsocketService } from './services/websocket.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  newMessage = '';
  messageList: string[] = [];

  constructor(private websocket: WebsocketService){
  }

  ngOnInit(){
    this.websocket.getNewMessage().subscribe((message: string) => {
      this.messageList.push(message);
    })
  }

  sendMessage() {
    this.websocket.sendMessage(this.newMessage);
    this.newMessage = '';
  }
}

websocket.service.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { io } from 'socket.io-client';

@Injectable({
  providedIn: 'root'
})
export class WebsocketService {

  public message$: BehaviorSubject<string> = new BehaviorSubject('');
  constructor() {}

  socket = io('http://localhost:5000');

  public sendMessage(message: any) {
    console.log('sendMessage: ', message)
    this.socket.emit('message', message);
  }

  public getNewMessage = () => {
    this.socket.on('message', (message) =>{
      this.message$.next(message);
    });

    return this.message$.asObservable();
  };
}

Finally, this is the error: Error

1

There are 1 answers

0
Zaga On BEST ANSWER

My computer is macOS and apparently, there is a service named AirPlay Receiver which uses port 5000. It was "trolling" my websocket server and causing the issue. Either you can disable it in System Preferences > Sharing > AirPlay Receiver or change the port on the server side. I never tried the second solution because when I checked port status I was already running the server.py which was misleading me.