反应调用烧瓶API导致CORS错误

问题描述 投票:0回答:2

在我的React应用程序中,我正在打电话给烧瓶API,但它被CORS挡住了,这给出了以下错误:to http:// localhost:5000/'从Origin'http'http:http:http'http:http:http:http'http: // Localhost:5173'已被CORS策略阻止:在请求的资源上没有“访问控制”标头。 回答:

import { useEffect, useState } from "react"; import axios from "axios"; import "./App.css"; function App() { useEffect(() => { // Define the API URL const apiUrl = "http://localhost:5000/"; // Make the Axios GET request axios .get(apiUrl) .then((response) => { // Handle the response data console.log(response); }) .catch((error) => { // Handle any errors console.error("Error fetching data:", error); }); }, []); return <div>Hello</div>; } export default App;

Flask:
from flask import Flask
from flask_cors import CORS
from flask import jsonify

app = Flask(__name__)

@app.route("/", methods=["GET"])
def get_example():
    """GET in server"""
    response = jsonify(message="Simple server is running")

    # Enable Access-Control-Allow-Origin
    response.headers.add("Access-Control-Allow-Origin")
    return response

if __name__ == '__main__':
   app.run()

我尝试过的事物:

直接添加响应的标题

在CORS(APP)中包装应用程序
  1. 用localhost @cross_origin装饰器
  2. app.config['cors_headers'] ='content-type'
  3. 上面的所有人一起
  4. 不管没关系,错误仍然存在。
  5. 我想知道了。由于我将VITE与React一起使用,因此有不同的代理程序和调用API。
  6. go to vite.config file

将以下内容列入导出默认decteconfig语句:

python reactjs flask cors
2个回答
1
投票
server: { proxy: { '/api': { target: 'http://127.0.0.1:5000', changeOrigin: true, secure: false, } }

确保目标是您所需的目标和端口。也不要使用“ Localhost”;改用IPv4地址。
    当调用API时,您必须在实际路线之前使用“/API”。例如,如果我的终点是本地主机:5000/您好,我会在我的API调用中放入“/api/hello”(使用fetch,axios等)。另外,请确保您的API端点在实际路线之前也具有 /API。如果我的路线看起来像这样: @app.route(“/hello”),请 @app.route(“/api/hello”),它应该起作用。
  1. 您必须将“应用程序”用cors作为flask_cors模块文档建议,或者如果需要用于特定路线,然后添加一个简单的装饰 @cross_origin()。
  2. app = Flask(__name__) CORS(app)
or

@app.route("/") @cross_origin() ....

https://flask-cors.readthedocs.io/en/latest/

0
投票

您可以添加键
rewrite

以避免更改所有路线

server: {
  proxy: {
    '/api': {
      target: 'http://127.0.0.1:5000',
      changeOrigin: true,
      secure: false,
      rewrite: (path) => path.replace(/^\/api/, ""),
    }
  }
}

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.