Hi
I wanted to build an Flask Next JS app like it is in Next.js Flask Starter – Vercel
When I make a get request to the server I will get a Cors Error.
My App: https://markb-52h2naa5g-mark-baumanns-projects.vercel.app/
Frontend:
// app/page.tsx
'use client'; // Add this directive at the top
import { useEffect, useState } from 'react';
const HomePage = () => {
const [data, setData] = useState<string>('');
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch('https://markb-4j93a7cux-mark-baumanns-projects.vercel.app/api/python');
const text = await response.text();
console.log(text);
setData(text);
} catch (error) {
console.error('Error fetching data:', error);
}
};
fetchData();
}, []);
return (
<div>
<h1>Response from Flask API:</h1>
<div dangerouslySetInnerHTML={{ __html: data }} />
</div>
);
};
export default HomePage;
Backend:
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app) # Dies aktiviert CORS für alle Routen
@app.route("/api/python")
def hello_world():
return "<p>Hello, World!</p>"
if __name__ == "__main__":
app.run(port=5000)
next Config:
module.exports = {
async headers() {
return [
{
// matching all API routes
source: "/api/:path*",
headers: [
{ key: "Access-Control-Allow-Credentials", value: "true" },
{ key: "Access-Control-Allow-Origin", value: "https://markb-4j93a7cux-mark-baumanns-projects.vercel.app/" },
{ key: "Access-Control-Allow-Methods", value: "GET,OPTIONS,PATCH,DELETE,POST,PUT" },
{ key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
]
}
]
}
};
Vercel.json:
{
"headers": [
{
"source": "/api/(.*)",
"headers": [
{ "key": "Access-Control-Allow-Credentials", "value": "true" },
{ "key": "Access-Control-Allow-Origin", "value": "https://markb-4j93a7cux-mark-baumanns-projects.vercel.app/" },
{ "key": "Access-Control-Allow-Methods", "value": "GET,OPTIONS,PATCH,DELETE,POST,PUT" },
{ "key": "Access-Control-Allow-Headers", "value": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" }
]
}
]
}
Full Code on GitHub GitHub - mark-baumann/markb