简体   繁体   English

为什么瓶子中的request.json返回None?

[英]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. 我有一个瓶子网络服务器,并且正在使用jQuery使用json来执行我的ajax请求,但是其中一个没有发送或另一个没有接收,我不确定是哪个。 My code is basically this: 我的代码基本上是这样的:

server.py 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 javascript

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

The javascript is trigger upon a button press and loginName is taken from an input box. 按下按钮后触发javascript,并从输入框中获取loginName。 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. 在js中,我做了console.log($ loginName)来确保它正确地选择了它,所以我假设问题出在一个jQuery调用中,或者我没有正确读取该数据。服务器端。 Both seem pretty simple an straightforward though so I'm not sure what I may be missing. 两者看起来都非常简单明了,所以我不确定我可能会缺少什么。

You can test your bottle method with $curl: 您可以使用$ curl测试您的bottle方法:

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

Bottle's request.json only works when the request's Content-type is application/json . Bottle的request.json仅在请求的Content-type为application/json (Your jQuery POST is probably using Content-type application/x-www-form-urlencoded .) (您的jQuery POST可能正在使用Content-type application/x-www-form-urlencoded 。)

In this case jQuery's .ajax() might be more appropriate than .post() . 在这种情况下,jQuery的.ajax()可能比.post()更合适。

您应该将其发布为json:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM