'How to solve django and angular cors errors

I'm developing application and got this error:

Access to XMLHttpRequest at 'https://subdomain.domain.org/api/parks/?page_size=6&page_number=1' from origin ''https://subdomain.domain.org' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Django Config

setting.py:

INSTALLED_APPS = [
  ...
  'corsheaders',
  ...
]
MIDDLEWARE = [
  ...
  'corsheaders.middleware.CorsMiddleware',
  'django.middleware.common.CommonMiddleware',
  ...
]
ALLOWED_HOSTS = ['app_name-backend.herokuapp.com']
CORS_ALLOWED_ORIGINS = [
  'https://app_name-frontend.herokuapp.com',
  'https://subdomain.domain.org',
]
CORS_ALLOW_ALL_ORIGINS = False

Angular Requests

service.ts:

getParks(filters: any=null, parameters:any=null): Observable<any> {
  ...
  var httpHeaders = new HttpHeaders();
  httpHeaders.set('Content-Type', 'application/json');
  httpHeaders.set('Access-Control-Allow-Origin', '*');

  var requestUrl = this.baseServiceUrl + this.serviceUrl;
  return this.httpClient.get<any>(requestUrl, { params: httpParams, headers: this.httpHeaders })
    .pipe(
      ...
    ),
    catchError(this.handleError<Park[]>('Park getParks', []))
  );
 }

The front and back are hosted on heroku

Any idea how to fix it ? Thanks in advance.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source