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.
localhostand127.0.0.1are the same thing on your machine? Maybe try running Django in0.0.0.0 8000way.