简体   繁体   English

POST json 数据到 Bottle

[英]POST json data to Bottle

I am a newbie to Bottle and sort of to Python as well and I am trying create an app whenever I click a button, an AJAX is fired and POST a json to server and store it using SQLite.我是 Bottle 的新手,也是 Python 的新手,每当我单击按钮时,我都会尝试创建一个应用程序,触发 AJAX 并将 json POST 到服务器并使用 SQLite 存储它。

However, at current stage, I am trying to figure out how do I successfully received the data in the server.但是,在当前阶段,我试图弄清楚如何成功接收服务器中的数据。

On the client side, I have the following send_data function written in JavaScript.在客户端,我有以下用 JavaScript 编写的 send_data 函数。

function send_data(feedback) {
    $.ajax({
        url: "/feedback",
        type: "POST",
        data: JSON.stringify(feedback),
        contentType: "application/json",
        success: function() {
            alert("Feedback successfully stored in the server!");
        },
        error: function() {
            alert("Feedback failed to store back in the server!");
        },          

}

The passed in parameter feedback looks something like {"id1": 1, "id2": 2} .传入的参数feedback看起来像{"id1": 1, "id2": 2}

On the server side, I have a feedback.py file and the code is在服务器端,我有一个feedback.py文件,代码是

from bottle import request, route, run
@route('/feedback', method='POST')

def feedback():
    comments = request.json
    print comments

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

Right now, I just want to check if I have received the data successful.现在,我只想检查是否已成功接收数据。 But everytime, when I click that botton, I receive the following error但是每次当我点击那个按钮时,我都会收到以下错误

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/feedback. This can be fixed by moving the resource to the same domain or enabling CORS.

OPTIONS http://localhost:8080/feedback [HTTP/1.0 405 Method Not Allowed 2ms]

I am not sure if it's because I am not using the element <form> .我不确定是不是因为我没有使用元素<form> That botton is technically just an image.从技术上讲,那个按钮只是一个图像。 Every time I click that image, send_data() function is fired.每次单击该图像时, send_data()触发send_data()函数。

Anyone can help?任何人都可以帮忙吗? I really appreciate it.对此,我真的非常感激。 Thank you!谢谢!

Cross Origins Requests are restricted as a security measure by the browser.作为一种安全措施,跨域请求受到浏览器的限制。 It is possible to overcome that by setting an Access-Control-Allow-Origin header.可以通过设置Access-Control-Allow-Origin标头来克服这个问题。 You can can use bottle-cors or create a decorator like the following on your server code (Python/bottle):您可以使用Bottle-cors或在您的服务器代码(Python/bottle)上创建如下所示的装饰器:

def enable_cors(fn):
  def _enable_cors(*args, **kwargs):
      response.headers['Access-Control-Allow-Origin'] = '*'
      response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
      response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'

      if request.method != 'OPTIONS':
          # actual request; reply with the actual response
          return fn(*args, **kwargs)

  return _enable_cors

and then with your example:然后用你的例子:

from bottle import request, route, run
@enable_cors
@route('/feedback', method='POST')

def feedback():
    comments = request.json
    print comments

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

Note that it's best to allow specific origins instead of using * .请注意,最好允许特定来源而不是使用*

You can read more about Cross-Origin Resource Sharing (CORS) here您可以在此处阅读有关跨域资源共享 (CORS) 的更多信息

You can make this work by disabling the Cross-origin restrictions.您可以通过禁用跨域限制来完成这项工作。

On safari, open the Develop panel, and check disable cross-origin restrictions, or use a browser like Firefox.在 safari 上,打开开发面板,勾选禁用跨域限制,或使用 Firefox 等浏览器。

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

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