0
votes

I have configured django rest framework with python 3. And the API is working fine in postman. But am facing a cross domain issue, when I call this api through my angualar 6 project.

OS: Mac OS

I have included oauth2 for authentication. It works well with postman

API Url: http://127.0.0.1:7777/api/v1/token/

Angular 6 website url: http://localhost:5000/#/login

When I called this with angualrjs it shows the following error.

Mozilla:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:7777/api/v1/token/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

Safari:

Failed to load resource: Origin http://localhost:5000 is not allowed by Access-Control-Allow-Origin.
XMLHttpRequest cannot load http://127.0.0.1:7777/api/v1/token/. Origin http://localhost:5000 is not allowed by Access-Control-Allow-Origin.

Chrome:

 Failed to load http://127.0.0.1:7777/api/v1/token/: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5000' is therefore not allowed access.

python settings.py cors related parts:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'django.contrib.flatpages',
    'widget_tweaks',
    'rest_framework',
    'oauth2_provider',
    'corsheaders',
] + get_core_apps() 
SITE_ID = 1


ALLOWED_HOSTS = ['127.0.0.1']
CORS_ORIGIN_WHITELIST = ('localhost:5000')
CORS_ORIGIN_ALLOW_ALL = True



MIDDLEWARE_CLASSES = [

    'django.middleware.security.SecurityMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    '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',
]

I have also installed oscarcommerce, oauth2, django rest framework. I have configured three other websites in my system with angularjs6 and python 2.7. All are working fine. This issue is coming only on this python 3 project.

2

2 Answers

0
votes

Add the below code in your settings.py

# Corsheaders settings
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = ('*')

it will work....

0
votes

Try This:

ALLOWED_HOSTS = []

CORS_ORIGIN_WHITELIST = (    
'127.0.0.1:7777',
'localhost:5000')

CORS_ORIGIN_ALLOW_ALL = True

Also Refer to this link for more information.