I am working on a React frontend to chart some data from a fastapi backend. I am using a couple of dropdown components to change the month and year for the requested data. With the initial render the fetch request works fine and returns the data and the charts display. Once I change the dropdowns, I get the following CORS Policy Error in the browser console.
Access to fetch at 'https://fake-url.com/endpoint/' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
React code snippet with the fetch call:
const [month, setMonth] = useState(1);
const [year, setYear] = useState('2023');
const [revenueData, setRevenueData] = useState({});
useEffect(() => {
const inputs = {
"month": month,
"year": year,
"duration": 1
}
const myHeaders = new Headers();
myHeaders.append("X-API-KEY", "fake-api-key");
myHeaders.append("Content-Type", "application/json");
const requestOptions = {
method: 'POST',
headers: myHeaders,
body: JSON.stringify(inputs),
redirect: 'follow'
};
fetch("https://fake-url.com/endpoint/", requestOptions)
.then(response => response.json())
.then(data => {
setRevenueData((data))
}).catch(error => {
console.log('error', error)
});
}, [month, year]);
I confirmed that I am using CORSMiddleware in fastapi with the following settings:
app.add_middleware(HTTPSRedirectMiddleware)
app.add_middleware(
CORSMiddleware,
allow_origins=['*'],
allow_methods=['*'],
allow_headers=['*']
)
I also confirmed that the backend is returning access-control headers for preflight with an options request in postman as shown:
UPDATE
The network panel shows that the second request preflight is successful but ultimately fails in an Internal Server Error. Which lead me to:
https://fake-url.com
. You need to add the headers to the serverhttps://fake-url.com
. If you do not control or ownhttps://fake-url.com
you need to convince whoever does to add them. This is the whole purpose of CORS If this is not the case you need to explicitly add that information to your post to avoid confusion and more debugging details as to why your browser isn't respecting the headers it is given. – Bestiaryhttps://fake-url.com
from the preflight request. I made a couple of words bold in the sentence prior to emphasize this. I get that CORS headers need to be coming from the backend server. Which is why I looked at my fastapi implementation first. Sorry it is a confusing situation for me. If it wasn't so, I probably would not be asking for help from the community here... can you point me in the direction of how I might troubleshoot further? – Bondmaid