Saqib Ali Saqib Ali - 2 months ago 7
Python Question

Why won't my Angular front-end pass correct $http.get parameters to Django back-end?

I have a Web Application made up of front-end client written in Angular/Javascript and a back-end server written in Python/Django.

I'm trying to do a simple http GET request from the client to the server and it is not working. The reason it is failing is because for some unknown reason, the parameters are not being passed correctly.

Here is the line of code being called on my client:

$http.get(API + '/api/getProfile', {'profileId':5}).then(console.log('A'), console.log('B'));


And here are the relevant lines of code on my server:

class GetProfileAPI(views.APIView):
def get(self, request, *args, **kwargs):
logger.info("request.get_full_path() = %s" % request.get_full_path())
profile_id_arg = request.GET.get('profileId')
logger.info("profile_id_arg = %s (%s)" % (profile_id_arg, type(profile_id_arg)))
# Do something here if profile_id_arg is not None.


When I run this code, I expect
profile_id_arg
on the server side to be the string
5
. But instead look at the output that I get:

request.get_full_path() = /api/getProfile
profile_id_arg = None (<type 'NoneType'>)


Why isn't
profile_id
being received properly and how can I fix this? Code example would be helpful.

Answer

A HTTP GET request can't contain data to be posted to the server. However you can add a query string to the request.

 $http.get(API + '/api/getProfile', {params:{'profileId':5}})
      .then(function (response) { /* */ })...

OR

$http({ 
     url: API + '/api/getProfile', 
     method: "GET",
     params: {'profileId':5}
  });

check here1 and check here2