Flask:XMLHttpRequest at '...' from origin has been blocked by CORS policy No 'Access-Control-Allow-Origin' header is present on the requested resource

Flask:XMLHttpRequest at '...' from origin has been blocked by CORS policy No 'Access-Control-Allow-Origin' header is present on the requested resource

我目前正在尝试在我的 RaspberryPi 上安装一个小型服务器 运行 并在局域网内从我的 PC 访问它。

我在访问 Raspberry 时收到以下错误,其中 index.html 显示给我就好了。显然我的“resetList”端点似乎有问题。

我也尝试了 Solve Cross Origin Resource Sharing with Flask 解决方案,但它对我不起作用。提前谢谢你。

我有以下 Python 代码:

gevent.monkey.patch_all()
from flask import Flask, render_template
from flask_socketio import SocketIO
import dbfunctions as db
import json
from flask_cors import CORS


app = Flask(__name__, template_folder='./build', static_folder='./build/static')
CORS(app)
socket_io = SocketIO(app)


@app.route('/', methods=['GET', 'POST', 'PUT'])
def index():
    return render_template('index.html')


# receiving messages
@socket_io.on('resetList')
def reset_list():
    database = r"data.db"
    conn = db.create_connection(database)
    with conn:
        data = db.get_data_without_initial(conn)
        fields = ["id", "name", "profit", "sum", "high", "maxProfit", "last_update"]
        json_list = []
        for i in range(len(data)):
            item_to_add = {fields[j]: data[i][j] for j in range(len(fields))}
            json_list.append(item_to_add)
        json.dumps(json_list)
        socket_io.emit('receivedData', json_list)


if __name__ == '__main__':
    socket_io.run(app, host='0.0.0.0', port=5000, debug=True)


我找到了解决方案,问题不是我的 python 代码,而是我的 java 代码:/ 简单添加“传输:[”轮询“]”解决问题

import io from "socket.io-client";
let endPoint = "http://localhost:5000";
let socket = io.connect(`${endPoint}`, { transports: ["polling"] });

function receiveData(cb) {
  socket.on("receivedData", (resp) => cb(resp));
}

export { receiveData };