I’m currently working on a project where I have a frontend application running on http://localhost:3000
and a backend API on http://localhost:8000
. I’m encountering a CORS issue when trying to make requests from my frontend to the backend API.
Here’s the error message I’m receiving in the browser’s console:
Access to XMLHttpRequest at ‘http://localhost:8000/api/list-accounts’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
I I want to retrieve account data from django and display it in a React component. I’ve set up a Redux store to manage the state of my application, and I’m using Redux Thunk for asynchronous actions.
This is the Redux action for fetching Account data:
export const fetchAccounts = () => {
return async (dispatch: Dispatch) => {
try {
dispatch(fetchAccountsRequest()); // Dispatch a request action
const response = await axios.get(`${API_BASE_URL}/list-accounts`, {
withCredentials: true,
});
const accounts = response.data;
dispatch(fetchAccountsSuccess(accounts));
} catch (error) {
dispatch(fetchAccountsFailure(error));
}
};
};
const fetchAccountsRequest = () => ({
type: ActionTypes.FETCH_ACCOUNTS_REQUEST,
});
const fetchAccountsSuccess = (accounts: Account[]) => ({
type: ActionTypes.FETCH_ACCOUNTS_SUCCESS,
payload: accounts,
});
const fetchAccountsFailure = (error: any) => ({
type: ActionTypes.FETCH_ACCOUNTS_FAILURE,
payload: error,
});
export function CardWithAccounts() {
const dispatch = useAppDispatch();
const accounts = useAppSelector((state:RootState) => state.accounts.accounts)
const loading = useAppSelector((state: RootState)=> state.accounts.loading)
useEffect(() => {
dispatch(fetchAccounts())
}, [dispatch])
if (loading) {
return <div>Loading...</div>
}
return ( <div></div>)
In my component called CardWithAccounts
, I’m using hooks to access the account data from the Redux store. My goal is to map through this data and render it in a card, displaying account details.
I’ve already tried several CORS configurations on the django backend, but I still can’t seem to get rid of this error.
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000",
]
CORS_ALLOW_CREDENTIALS = True
"corsheaders.middleware.CorsMiddleware",
ALLOWED_HOSTS = ["127.0.0.1","localhost"]
Also this is my Redux dev tools logs:
NOTE!:
I have other API calls in my app that work properly, this is the only request i get a CORS error.
2
Answers
I was missing a / on:
Fix:
GO with these settings of Django in
settings.py