400 (BAD REQUEST) Error with Flask SocketIO

86 Views Asked by At

I am using python socket server with flask_socketio. And my client side is vuejs where using socket.io-client. I have created a socket url in my production server. But while connecting it in vue js then it's throwing 400 Bad request. But if I call the url from a browser direct then it's returning data. Please give a solution that how to use it from my vuejs application.

It was giving cors error first, I have resolved it. But I could not resolve 400 error. Need help.

socket server code:

from flask import Flask, render_template, request, jsonify
from flask_socketio import SocketIO


app = Flask(__name__)
socketio = SocketIO(app, cors_allowed_origins="my-socket-url")

# Event handler for when a client connects to the server
@socketio.on('connect')
def handle_connect():
    print('Client connected')
    # You can add logic to handle socket connections here

# Event handler for when a client disconnects from the server
@socketio.on('disconnect')
def handle_disconnect():
    print('Client disconnected')
    # You can add logic to handle socket disconnections here

# Custom event handler
@socketio.on('custom_event')
def handle_custom_event(data):
    print('Received custom event:', data)
    # Broadcast the data to all connected clients
    socketio.emit('custom_response', data.get('responseData'))

# Define a route to handle both HTTP requests and WebSocket connections
@app.route('/socket.io/', methods=['GET', 'POST'])
def handle_root():
    if request.method == 'GET':
        # Handle HTTP GET request
        return 'Hello, this is the data you requested!'
    elif request.method == 'POST':
        # Handle HTTP POST request
        # You can add logic to handle POST requests here
        return jsonify({'message': 'Received POST request'})

if __name__ == '__main__':
    # Start the Socket.IO server using Eventlet
    socketio.run(app, host='0.0.0.0', port=5000, debug=True)

vuejs code:

const socket = io('my-socket-url'); 

created(){

socket.on('custom_response', (data) => {
        console.log(data)
        // Update the message in your Vue.js component
        let newObj = {
            content: data.content,
            timestamp: "1696233096400",
            type: "sms"
        }
        let targetObjectIndex = this.items.findIndex(item => item.phoneNumber === data.phoneNumber)
        this.items[targetObjectIndex].dataSet.push(newObj)
    });


}
0

There are 0 best solutions below