I'm trying to get data using axios
, but facing the following error:
No 'Access-Control-Allow-Origin'
I have tried to find a solution, but nowhere I found a proper solution including FastAPI, React and Axios.
Here is my backend:
origins = ['https://localhost:3000', 'https://localhost:8080']
app.add_middleware(
CORSMiddleware,
allow_origins = [origins],
allow_credentials = True,
allow_methods = ["*"],
allow_headers = ["*"]
)
@app.get('/')
def root():
return {
"Data" : "Working!"
}
Below is my frontend:
const message = async () => {
try {
let res = await axios.get("http://127.0.0.1:8080/");
let result = res.data;
console.log(result);
} catch (e) {
console.log(e);
}
};
useEffect(() => {
message();
}, []);
The error:
Access to XMLHttpRequest at 'http://127.0.0.1:8080/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Now I'm using it locally adding proxy in package.json
file. But in production, it doesn't work. However, I need a proper solution for production level without using proxy.
Please help me to solve this error.