kryptobs2000
kryptobs2000

Reputation: 3537

Why is request.json in bottle returning None?

I have a bottle web server and am using jQuery to do my ajax requests using json, but either one is not sending or the other is not receiving, I'm not sure which. My code is basically this:

server.py

@route("/jsontest", method="POST")
def jsontest():
  print(request.json)

Always prints None, the request is going through of course, but it doesn't appear to be receiving any data.

javascript

$.post("/jsontest", {username: $loginName}, login_success)

The javascript is trigger upon a button press and loginName is taken from an input box. In the js I've done a console.log($loginName) to ensure it's actually selecting it properly and it is, so I'm assuming the problem is in that one jQuery call or I'm not reading the data properly on the server end. Both seem pretty simple an straightforward though so I'm not sure what I may be missing.

Upvotes: 1

Views: 3490

Answers (3)

H. U.
H. U.

Reputation: 637

You can test your bottle method with $curl:

curl -i -H "Content-Type: application/json" -X POST -d '{"UserName":"name","Password":"password"}' http://hostname/jsontest

Now you can print the request data by:
print request.json

Upvotes: 6

iurisilvio
iurisilvio

Reputation: 4987

You should POST it as json:

$.post("/jsontest", JSON.stringify({username: $loginName}), login_success)

Upvotes: 0

ron rothman
ron rothman

Reputation: 18168

Bottle's request.json only works when the request's Content-type is application/json. (Your jQuery POST is probably using Content-type application/x-www-form-urlencoded.)

In this case jQuery's .ajax() might be more appropriate than .post().

Upvotes: 1

Related Questions