如何从反应中允许python烧瓶socketio中的cors-origin-policy

Posted

技术标签:

【中文标题】如何从反应中允许python烧瓶socketio中的cors-origin-policy【英文标题】:how to allow cors-origin-policy in python flask socketio from react 【发布时间】:2021-07-07 06:16:34 【问题描述】:

这是我的 server.py 文件。我已经使用 socketio 从反应应用程序中调用。

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)

但是当我从 react 应用程序调用这个 socketio 时,我收到以下错误。

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.

我的反应代码如下:

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
        ;
    

如何解决 corse 原产地政策错误?

【问题讨论】:

【参考方案1】:

Cors 错误可以像这样处理

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();
  
);

参考:Socket-cors-handling

【讨论】:

我已经从 python 端处理了 cors 错误。检查一下。

以上是关于如何从反应中允许python烧瓶socketio中的cors-origin-policy的主要内容,如果未能解决你的问题,请参考以下文章

我如何在 MySql 中允许外部连接?

Python 函数名中允许的字符

为啥列表中允许使用尾随逗号?

在捕获keydown事件时如何在文本框中允许退格

烧瓶 socketio CORS

为啥在 python 切片中允许非整数内置类型?