在我的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;
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)中包装应用程序
将以下内容列入导出默认decteconfig语句:
server: {
proxy: {
'/api': {
target: 'http://127.0.0.1:5000',
changeOrigin: true,
secure: false,
}
}
确保目标是您所需的目标和端口。也不要使用“ Localhost”;改用IPv4地址。
app = Flask(__name__)
CORS(app)
or
@app.route("/")
@cross_origin()
....