【发布时间】:2020-10-31 17:26:37
【问题描述】:
我正在开发一个基于 Angular 的应用程序通过 Socket.IO 与 Flask 通信的项目。我的烧瓶代码如下:
from flask import Flask, render_template
from flask_socketio import SocketIO
from flask_cors import CORS
import json
app = Flask(__name__)
CORS(app)
#app.config['SECRET_KEY'] = 'vnkdjnfjknfl1232#'
socketio = SocketIO(app)
@app.route('/')
def sessions():
return render_template('index.html')
def messageReceived(methods=['GET', 'POST']):
print('message was received!!!')
@socketio.on('my event')
def handle_my_custom_event(json, methods=['GET', 'POST']):
json["user_name"]='Asad'
json["user_input"]='My Server'
print('received my event: ' + str(json))
socketio.emit('my response', json, callback=messageReceived)
if __name__ == '__main__':
socketio.run(app, debug=True, host='localhost', port = 5000)
当我尝试加载我的 Angular 项目时,它立即显示与 CORS 相关的错误。我已经尝试安装 Moesif Origin & CORS Changer 并将 CORS 包含到服务器代码中,可以看出但没有任何改进。 Angular 代码取自 [https://tutorialedge.net/typescript/angular/angular-socket-io-tutorial/][1]
但是,我没有使用该教程中显示的 websocket 服务器,因为正在使用 Flask 端的服务器:
显示的错误是: 跨域请求被阻止:同源策略不允许在 http://localhost:5000/socket.io/?EIO=3&transport=polling&t=NCws9C7 读取远程资源。 (原因:CORS 请求未成功)。 [1]:https://tutorialedge.net/typescript/angular/angular-socket-io-tutorial/
【问题讨论】:
标签: angular flask socket.io cors