Search code examples
djangoangularangular-servicesangular7

Connect local django backend with angular 7


I exposed API in Django backend. I want to get that API request from Angular 7. so I implemented the code that

this.HttpClient.get('Http://127.0.0.1:8000/myapp/posts') .subscribe( (data:any[]) => { console.log(data) } )

But I'm getting an error that

Access to XMLHttpRequest at 'http://127.0.0.1:8000/myapp/posts' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false, …}error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …}headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}message: "Http failure response for (unknown url): 0 Unknown Error"name: "HttpErrorResponse"ok: falsestatus: 0statusText: "Unknown Error"url: null__proto__: HttpResponseBase

Could anyone suggest any solution to solve this error?


Solution

  • When sending HTTP requests from your front-end application, using the browser's fetch API, the Axios client or the jQuery $.ajax() method (a wrapper for the JavaScript XHR interface), to your back-end API built with Django REST framework the web browser will throw an error related to the Same Origin Policy.

    Cross Origin Resource Sharing or CORS allows client applications to interface with APIs hosted on different domains by enabling modern web browsers to bypass the Same origin Policy which is enforced by default.

    Ref how to do it here: https://www.techiediaries.com/django-cors/

    you need to add a middleware file app/cors.py:

    class CorsMiddleware(object):
        def process_response(self, req, resp):
            response["Access-Control-Allow-Origin"] = "*"
            return response
    

    This will add an Access-Control-Allow-Origin:* header to every Django request but before that you need to add it to the list of middleware classes:

    MIDDLEWARE_CLASSES = (
        #...
        'app.CorsMiddleware' 
    )
    

    Then install the django-cors-headers

    Start by installing django-cors-headers using pip

    pip install django-cors-headers