首页 > 解决方案 > Angular中的CORS错误-基于flask socketIO

问题描述

我正在开发一个基于 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 端的服务器:

显示的错误是:Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/socket.io/?EIO=3&transport=polling&t=NCws9C7。(原因:CORS 请求未成功)。[1]:https ://tutorialedge.net/typescript/angular/angular-socket-io-tutorial/

标签: angularflasksocket.iocors

解决方案


我对 CORS 有类似的经历,这是因为我没有正确配置我的设置。

提示:检查您的代理配置文件检查您的代理配置密钥

你可以阅读这个摘要


推荐阅读