Reputation: 4845
I have just deployed my NextJS-frontend/FastAPI-backend app on Vercel, and I am currently running into an issue that seems related to CORS that is giving me a 405 Method Not Allowed
when I try to POST/GET to my FastAPI backend from the frontend.
For context, this works in my local development environment where the frontend is located in localhost:3000
, and the backend is localhost:8000
Below is the attached image of the error.
I have tried a few things, this is my next.config.js
at the root of my directory
/** @type {import('next').NextConfig} */
const nextConfig = {
rewrites: async () => {
return [
{
source: "/:path*",
destination:
process.env.NODE_ENV === "development"
? {NEXT_PUBLIC_LOCALHOST_URL} + "/:path*"
: "/",
}
];
},
async headers() {
return [
{
// matching all API routes
source: "/:path*",
headers: [
{ key: "Access-Control-Allow-Credentials", value: "true" },
{ key: "Access-Control-Allow-Origin", value: "*" },
{ key: "Access-Control-Allow-Methods", value: "*" },
{ key: "Access-Control-Allow-Headers", value: "*" },
]
}
]
}
};
module.exports = nextConfig;
Then in my main.py
which is the entry point to my FastAPI backend, I have the following policies:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from api.v1.endpoints import text, image, video, index
app = FastAPI()
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["*"]
)
@app.get("/")
async def root():
return {"message": "Welcome to the API!"}
app.include_router(text.router)
app.include_router(image.router)
app.include_router(video.router)
app.include_router(index.router)
Interestingly enough, if I try to use cURL and send a POST/GET request to the endpoints, I get nothing in return.
Upvotes: 0
Views: 291
Reputation: 2353
Wildcards doesn't work with allow_credentials=True
in FastAPI's CORSMiddleware.
You should specify allowed origins explicitly
Upvotes: 0