简体   繁体   English

在python瓶中接收JSON

[英]Receive JSON in python Bottle

I am trying to do a JSON post to my Bottle server. 我正在尝试将JSON发布到我的Bottle服务器。

from bottle import request, route, run
@route('/feedback', method='POST')
def feedback():
    data = request.json
    print data

run(host='localhost',port=8080)

In the client side, I have 在客户端,我有

$('#user_feedback').submit(function() {
  var feedback = {"id": 1}
  $.ajax({
     type: "POST",
     url: "http://localhost:8080/feedback",
     data: feedback
 });
 return false;
});

I am returning false here because I don't want the page to be redirected. 我在这里返回false,因为我不希望页面被重定向。

However, the data I received in my Bottle server is always None when printed out. 但是,打印出来时,我在Bottle服务器中接收到的data始终为None Please help. 请帮忙。 Thank you. 谢谢。

request.json expects the content type of the request to be application/json . request.json希望请求的内容类型为application/json So to make it work, you should set the contentType property of your request to application/json and stringify your data : 因此,要使其正常工作,您应该将请求的contentType属性设置为application/json并对数据进行字符串化:

$.ajax({ 
    type:"POST",
    contentType: "application/json",
    url:"/feedback",
    data: JSON.stringify(feedback)
});

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

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