How to parse an Angular POST request in WebApp2

All we need is an easy explanation of the problem, so here it is.

How do I get data from my Angular POST request in Google App Engine WebApp2? self.request.body returns a string, and self.request.get(key) returns nothing.

The Angular code that submits the POST is:

$http.post("/mail", {request_name: 'Test Name', request_body: 'Test Body'});

Then these two lines in my WebApp2 handler:

print "1:  " + self.request.body
print "2:  " + self.request.get('request_name')

Print this:

1:  {"request_name":"Test Name","request_body":"Test Body"}
2:  

What is the best way get data from the POST body? Or should I send the request differently?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Judging from your first print, it seems that Angular is sending the data in JSON format. Webapp2 will not parse this data for you. For your particular request, you can do:

import json
d = json.loads(self.request.body)
v = d.get(key)

If you want to be able to access the POST data using self.request.POST.get(key), you probably need to submit the data as form data. See this SO answer for more information about that.

Method 2

I always use self.request.get and able to get the data from GET/POST method, maybe you send the data in different format that only accessible by self.request.body?

Method 3

You can try this:

 self.request.POST.get(key) # POST requests
 self.request.GET.get(key)  # GET requests

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply