skip to Main Content

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:

Inspector

Log monitor

NOTE!:
I have other API calls in my app that work properly, this is the only request i get a CORS error.

2

Answers


  1. Chosen as BEST ANSWER

    I was missing a / on:

     try {
            dispatch(fetchAccountsRequest()); 
            const response = await axios.get(`${API_BASE_URL}/list-accounts`, {
              withCredentials: true, 
            });
    
    

    Fix:

    const response = await axios.get(`${API_BASE_URL}/list-accounts/`
    

  2. GO with these settings of Django in settings.py

    DEBUG = True
    
    ALLOWED_HOSTS = ["*"]
    
    
    # Application definition
    
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'rest_framework',
        'corsheaders', # <-------- this
        'myapp',
    ]
    
    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'corsheaders.middleware.CorsMiddleware', # <-------- this
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
        'sales_company_app.get_user_instance.RequestMiddleware',
    ]
    
    
    
    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework.authentication.TokenAuthentication',
        ),
    }
    
    
    CORS_ORIGIN_ALLOW_ALL = True # <-------- this
    CORS_ALLOWED_ORIGINS = [
        "http://localhost:3000",    # React (FrontEnd Url) # <-------- this
    ]
    
    CORS_ALLOW_HEADERS = '*' # <-------- this
    CSRF_TRUSTED_ORIGINS = ["http://192.168.1.155:8000/"] # (Api Base Url) <-------- this (allow csrf_token) for doing whitelist
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search