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',
        'Accept': 'application/json'
      })
    }
    
    @Injectable()
    export class DbService {
          
      constructor(private httpClient: HttpClient) { }
    
      addConsumerMongodb(consumer: Post): Observable<Post> {
        return 
this.httpClient.post<Post>(`http://localhost:8000/apdjango/`, 
JSON.stringify(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'^apdjango/', handle_consumer),
        url(r'^.*', TemplateView.as_view(template_name="home.html"), 
name="home")
    ]

This file is in the same folder as `views` and `models` and `serializers`. 
I have another `urls.py` in the folder that has `settings.py` and `wsgi.py` 
with the following content:

    from django.conf.urls import url, include 
    
    urlpatterns = [ 
        url(r'^', include('apdjango.urls')),
    ]

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

    POST http://localhost:8000/apdjango/ 400 (Bad Request)
    
    ERROR kK {headers: La, status: 400, statusText: 'Bad Request', url: 
'http://localhost:8000/apdjango/', ok: false, …}

I thought the problem was to do with the URLs or / or $ which is why I just 
copied the link that works in Postman and stuck it literally in my Angular 
post service method.

I have been through every Q&A on stackoverflow and tried their solutions 
and suggestions, but I still cannot fix this.

*Can someone please help me?*

-------------------

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_ALLOW_ALL_ORIGINS = 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 = ()

I also have this: `ALLOWED_HOSTS = ['*']`

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/23c029f5-de07-40b4-820d-64a95712be01n%40googlegroups.com.

Reply via email to