CORS errors in an Angular frontend calling a Django backend in a Linux server.
CORS errors in an Angular frontend calling a Django backend in a Linux server, you can follow these steps:
Install Django CORS headers:
Copy code
pip install django-cors-headers
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 ]
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.
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', ]
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.