0
votes

I'm developing back-end API with Django Rest Framework and front-end with Angular 2. The django server runs on localhost:8000 and the angular server runs on localhost:3000. When I try to access API using angular 2, it gives me the following error:

customerregister:1 XMLHttpRequest cannot load http://127.0.0.1:8000/user/signup. 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:3000' is therefore not allowed access.

What I want to ask is how to integrate the development of Django Rest API and angular 2 project.

1

1 Answers

2
votes

First install : https://github.com/ottoyiu/django-cors-headers.

Apply your apps:

INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)

Then change your settings for middleware:

MIDDLEWARE = [  # Or MIDDLEWARE_CLASSES on Django < 1.10
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
]

Restart server and it must work.