I am trying to send a post request from my nextjs app local server to my FastAPI local server, but i still get the cors error, the thing is when i sent the same request to my prod url of my azure web app api (same api but hosted on azure) from my nextjs app i dont get any cors errors
Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/charger/get_status_by_ou/0000-0016' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
C:Userskenkiklantportaal2testing2azuretestingazurepagesrealtime.tsx:181 Error fetching data: AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}
nextJsHandleConsoleError @ client.js:85
fetchData @realtime.tsx:181
await in fetchData
Realtime.useEffect @
POST http://127.0.0.1:8000/api/charger/get_status_by_ou/0000-0016 net::ERR_FAILED
This is how i send the request in my frontend
const fetchData = async () => {
try {
if (!ouData) {
console.error("OU data is empty!");
return;
}
console.log(`url: ${process.env.NEXT_PUBLIC_LOCAL_URL} `);
const statusResponse = await axios.post(
`${process.env.NEXT_PUBLIC_LOCAL_URL}/api/charger/get_status_by_ou/${ouData}`,
{},
{
headers: {
Authorization: `Bearer ${apiToken}`,
Accept: 'application/json',
}
}
);
console.log("Status Data:", statusResponse.data);
And my fast api main.py
from fastapi import FastAPI, Query, HTTPException
from database import get_db_connection
import traceback
import logging
from fastapi.middleware.cors import CORSMiddleware
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
origins = [
"http://localhost:3000"
]
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=origins, # Allows requests from these origins
allow_credentials=True,
allow_methods=["*"], # Allow all HTTP methods (GET, POST, etc.)
allow_headers=["*"], # Allow all headers
)