CORS errors in an Angular-Django in a Linux server


  • Python
  • Django
    • 2
    • Verified
    • Posted by
    • TimeMarch 31, 2023, 10:13 p.m.
    • StatusActive

    Snippet Description

    CORS errors in an Angular frontend calling a Django backend in a Linux server.

    Code

      CORS errors in an Angular frontend calling a Django backend in a Linux server, you can follow these steps:

      1. Install Django CORS headers:

        Copy code

        pip install django-cors-headers

      2. Add the middleware to your Django settings.py file:

        pythonCopy code

        MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', # add this line ]

      3. Allow the origins that should have access to your Django backend. In your Django settings.py file, add the following:

        pythonCopy code

        CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'http://localhost:4200', 'https://yourdomain.com', )

        This allows requests from http://localhost:4200 and https://yourdomain.com. You can add more origins to the list as needed.

      4. Add the CORS headers to your Django response. In your Django settings.py file, add the following:

        pythonCopy code

        CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ]

      5. Finally, restart your Django server and test your Angular frontend. You should no longer see CORS errors.

      Note: Remember to only allow trusted origins to prevent security vulnerabilities.

    Comments

    Related Posts

    PWADHWA

    Send SMS using Django-Python

    Python Django

    2 Aug. 14, 2022, 4:32 p.m.
    Proud

    Create Superuser in Django

    Python Django

    4 March 18, 2022, 5:42 p.m.
    PPPP

    Want to Hire our experts?

    We'll help you to grow your career and growth.
    SignUp Today