0

I write a simple view in Django Rest framework and test it in web browser:

@api_view(['Get', 'Post'])
@permission_classes((AllowAny,))
@method_decorator(csrf_exempt, name='dispatch')
def hello_world(request):
    print(request.data)
    if request.method == 'POST':
        return Response({"message": "Got some data!", "data": request.data})
    return Response({"id":201,"content":"Hello, World!"})

And tried to consume it with Ajax, using jQuery and AngularJs.

jQuery

For jQuery I use the code below:

                $.ajax({
                    type: "POST",
                    dataType: "json",
                    ContentType: "application/json",
                    url: "http://127.0.0.1:8000/test/",
                    "data": data,
                    success: function(inp_data, status, jqXHR){
                        console.log('success');
                        console.log(JSON.stringify(inp_data));
                        },
                    error: function(xhr, errMsg) {
                        console.log('failure');
                        console.log(errMsg);
                        console.log(xhr.status + ": " + xhr.responseText);
                        }
                    }); 

And receive:

1) in backend:

<QueryDict: {'key1': ['value1']}>
[26/Oct/2017 11:20:34] "POST /test/ HTTP/1.1" 200 15

2) in frontend console:

failure (11:20:35:881 | null)
  at public_html/index.html:132
error (11:20:35:887 | null)
  at public_html/index.html:133
0: undefined (11:20:35:888 | null)
  at public_html/index.html:134

So with jQuery I can send my data from frontend to backend, but truble to do it in reverse way.

AngularJs

I tried to make a get request with following codes for html:

<html ng-app="demo">
    <head>
        <title>Hello AngularJS</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
        <script src="hello.js"></script>
    </head>

    <body>
        <div ng-controller="Hello">
            <p>The ID is {{greeting.id}}</p>
            <p>The content is {{greeting.content}}</p>
        </div>
    </body>
</html>

and js:

angular.module('demo', [])
.controller('Hello', function($scope, $http) {
    console.log('wait for response');
    $http.get('http://127.0.0.1:8000/test/').
        then(function(response) {
            console.log('get response');
            $scope.greeting = response.data;
        });
    console.log('finished');
});

After running a code above I receive:

1)in backend:

<QueryDict: {}>
[26/Oct/2017 12:33:06] "GET /test/ HTTP/1.1" 200 36

2)in frontend console:

wait for response (12:33:06:150 | null)
  at public_html/hello.js:8
finished (12:33:06:163 | null)
  at public_html/hello.js:14

So why cannot I receive my DRF response in booth jQuery and AngularJS?

Update

Find it in chrome's console:

XMLHttpRequest cannot load http://127.0.0.1:8000/test. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8383' is therefore not allowed access.
:8383/favicon.ico Failed to load resource: net::ERR_EMPTY_RESPONSE

When I render AngularJs code through Django(with ading {% verbatim %}) instead of NetBeans(I like to use it for writing frontend), it works fine. So it looks like I should enable CORS if I wont Django Rest Framework to make friends with NetBeans IDE.

4
  • How does the response returned by Django look like? Commented Oct 26, 2017 at 10:42
  • If i type in terminal: $ curl 127.0.0.1:8000/test It returns: {"content":"Hello, World!","id":201} in same terminal So anyway server emit response Commented Oct 26, 2017 at 12:46
  • Any error in JS console? Is CORS enabled in Django? Commented Oct 26, 2017 at 20:28
  • Also, are you 100% positive that localhost and 127.0.0.1 are the same thing on your machine? Maybe try running Django in 0.0.0.0 8000 way. Commented Oct 26, 2017 at 20:30

2 Answers 2

1

The problem was deal with fact that I run my frontend from NetBeans. The NetBeans' console is pretty good, but chrome's one give me idea about CORS-conflict. I have no idea why didn't CORS-conflict display in django's output, but when I installed 'django-cors-headers' according to oficial docs and set:

CORS_ORIGIN_ALLOW_ALL=True

in my settings.py, it start work!!!

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

Comments

0

In django rest framework request, GET parameters are not present in the request.data. They are query parameters rather than data. So they are placed under request.query_params. Access data from request.query_params in get request

see the doc

try this to get both POST and GET data

@api_view(['Get', 'Post'])
@permission_classes((AllowAny,))
@method_decorator(csrf_exempt, name='dispatch')
def hello_world(request):
    if request.method == 'POST':
        print(request.data)
        return Response({"message": "Got some data in POST!", "data": request.data})
    if request.method == 'GET':
        print(request.query_params)
        return Response({"message": "Got some data in GET!", "data": request.query_params})
    return Response({"detail":"Invalid request type"}, status=400)

2 Comments

I have write that it's not problem for me to send data to server. The receiving data in frontend is problem, which is partially solved(see UPD).
are you saying that you are receiving the data at the server side and not able to see the response in the front end.right? If so please share your response. show your console output.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.