Django and Angular communication failure

I have developed a small Angular app with a service script to add a consumer form info to a MongoDB database:

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json'
  })
}

@Injectable()
export class DbService {
  
  baseMongodbApiUrl = "http://localhost:8000/api/apdjango";

  constructor(private httpClient: HttpClient) { }

  addConsumerMongodb(consumer: Post): Observable<Post> {
    return this.httpClient.post<Post>(`${this.baseMongodbApiUrl}` + `/handle_consumer`, consumer, httpOptions);
  }
}

I have also written this Django method in my views.py file to add a consumer:

@csrf_exempt
@api_view(['GET', 'POST', 'DELETE'])
def handle_consumer(request):
    if request.method == 'POST':
        try:
            consumer_data = JSONParser().parse(request)
            consumer_serializer = ConsumerModelSerializer(data=consumer_data)

            if consumer_serializer.is_valid():
                consumer_serializer.save()
                print(consumer_serializer.data)
                response = {
                    'message': "Successfully uploaded a consumer with id = %d" % consumer_serializer.data.get('id'),
                    'consumers': [consumer_serializer.data],
                    'error': ""
                }
                return JsonResponse(response, status=status.HTTP_201_CREATED)
            else:
                error = {
                    'message': "Can not upload successfully!",
                    'consumers': "[]",
                    'error': consumer_serializer.errors
                }
                return JsonResponse(error, status=status.HTTP_400_BAD_REQUEST)
        except:
            exceptionError = {
                'message': "Can not upload successfully!",
                'consumers': "[]",
                'error': "Having an exception!"
            }
            return JsonResponse(exceptionError, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

and of course I have put the url pattern in my urls.py:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api/apdjango$', handle_consumer),
    url(r'^.*', TemplateView.as_view(template_name="home.html"), name="home")
]

When I use postman to Post to http://localhost:8000/api/apdjango, it goes through and I see the success message, but when I invoke my Angular service method, I get:

POST http://localhost:8000/api/apdjango/handle_consumer 403 (Forbidden)

ERROR kK {headers: La, status: 403, statusText: 'Forbidden', url: 'http://localhost:8000/api/apdjango/handle_consumer', ok: false, …}

What am I doing wrong in that invocation? It's probably with the URLs or / or $ I think; right?


EDIT: My cors settings are as follows:

INSTALLED_APPS = [
    ...
    'corsheaders',
    'apdjango'
]


MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    ....
]

CSRF_COOKIE_SECURE = True

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = False
CORS_ORIGIN_REGEX_WHITELIST = ()
CORS_URLS_REGEX = '^.*$'
CORS_ALLOW_METHODS = (
    'GET',
    'POST',
    'PUT',
    'PATCH',
    'DELETE',
    'UPDATE',
    'OPTIONS'
)
CORS_ALLOW_HEADERS = (
    'x-requested-with',
    'content-type',
    'accept',
    'origin',
    'authorization',
    'x-csrftoken'
)
CORS_EXPOSE_HEADERS = ()
Back to Top