Can't get data in AngularJS format $ http.post in Django

I know this is a very simple question, but after spending my entire day I am asking this. I am just posting data using the following AngularJS code to Django:

$http.post('/data/creation', 
                    {
                html: 'a'

            }).
              success(function(data, status, headers, config) {
                // this callback will be called asynchronously
                // when the response is available
                  console.log(data);
                  console.log(status);
                  console.log(headers);
                  console.log(config);
              }).
              error(function(data, status, headers, config) {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
                  console.log(status);
                  console.log(data);
              });

      

and in django:

@csrf_exempt
def snippets_post(request):
    html = False
    css = False
    js = False
    JSONdata = False
    response = "You're looking at the results of question %s."
    if request.method == 'POST':
        try:
            JSONdata = request.POST.get('data', False) # it was [] in actual
        except:
            JSONdata = 'ERROR'

    return HttpResponse(JSONdata)

      

I am getting False as a response, "replacing the data with html in POST.get, the result is the same . " I don't know what's going on here. Can anyone help me here?

thank

+3


source to share


1 answer


In fact, when we post data from AngularJs with $ http POST, it posts data with content-type = "application / json" to the server. And Django doesn't understand this format. And therefore you cannot receive the sent data.

The solution is to change the title of the content type using the following configuration:



    app.config(['$httpProvider', function ($httpProvider) {
        $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
}]);

      

+4


source







All Articles