0

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The solution that you gave will solve the problem for localhost but will I have to do the same when I'll deploy my decoupled app on actual server. I have never deployed any code on actual server but have read the following guide. digitalocean.com/community/tutorials/…. In step 4, the guide tells how to config your server. It points the incoming request to the port where my django code will be running. Then how the user will have access to website.
This configuration will work on your server same thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.