【问题标题】:localhost CORS error using Flask and React使用 Flask 和 React 的 localhost CORS 错误
【发布时间】:2022-01-05 07:33:19
【问题描述】:

我在开发我的 React 应用程序时遇到了一些问题。在客户端,我使用 Axios 向 API(Flask)发出请求。

问题是我只有在将请求发送到 localhost API 时才经常收到 CORS 错误。我在 Heroku 中运行相同的 API,没有任何错误。

API 路由 = http://127.0.0.1:5000

客户端路由 = http://localhost:3000/#/

客户端代码:

const endpoint = process.env.REACT_APP_ENDPOINT;
// Fetch API data
const [data, setData] = useState([{}]);
useEffect(() => {
    axios.get(endpoint + "/api/rooms")
        .then((data) => {
            console.log("API endpoint data retrieved.");
            if (data[200] !== "No Rooms") {
                setData(data);
            }
        }).catch((err) => {
            console.error(err.message);
            console.log("No rooms retrieved from API endpoint.");
        });
}, [endpoint]);

服务器(Python)代码:

import os
from flask import Flask
from flask_socketio import SocketIO
from flask_cors import CORS, cross_origin
from dotenv import load_dotenv
from app_modules.util.rooms import Rooms

load_dotenv()

app = Flask(__name__, static_folder="/client/build")
app.config['SECRET_KEY'] = os.getenv("app_key")
app.config['CORS_HEADERS'] = "Content-Type"
ALLOWED_ORIGINS = os.getenv("ALLOWED_ORIGINS")

cors = CORS(app, resources={"/*": {"origins": ALLOWED_ORIGINS}}, support_credentials=True)

socketio = SocketIO(app,
                    cors_allowed_origins=ALLOWED_ORIGINS,
                    logger=False,
                    engineio_logger=False,
                    cors_credentials=True)

rooms = Rooms()


@app.route('/api/rooms')
@cross_origin(supports_credentials=True)
def home():
    return {"rooms": rooms.secure_api} if rooms.secure_api else {"200": "No Rooms"}

注意: ALLOWED_ORIGINS=*

但我不断收到此错误:

【问题讨论】:

  • ALLOWED_ORIGINS 的当前值是多少?
  • ALLOWED_ORIGINS=*

标签: reactjs python-3.x api flask cors


【解决方案1】:

在您的服务器代码更改

ALLOWED_ORIGINS = os.getenv("ALLOWED_ORIGINS")

ALLOWED_ORIGINS = ['localhost', '127.0.0.1']

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
  • 我得到同样的错误。
猜你喜欢
  • 1970-01-01
  • 2020-02-28
  • 2018-02-03
  • 2020-06-18
  • 2019-05-27
  • 1970-01-01
  • 1970-01-01
  • 2020-10-04
  • 2021-01-13
相关资源
最近更新 更多