【问题标题】:POST json data to BottlePOST json 数据到 Bottle
【发布时间】:2015-02-05 18:48:01
【问题描述】:

我是 Bottle 的新手,也是 Python 的新手,每当我单击按钮时,我都会尝试创建一个应用程序,触发 AJAX 并将 json 发布到服务器并使用 SQLite 存储它。

但是,在当前阶段,我正在尝试弄清楚如何在服务器中成功接收数据。

在客户端, 我有以下用 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!");
        },          

}

传入的参数feedback 类似于{"id1": 1, "id2": 2}

在服务器端,我有一个feedback.py 文件,代码是

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

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

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

现在,我只想检查我是否成功接收到数据。但是每次,当我点击那个按钮时,我都会收到以下错误

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]

我不确定是不是因为我没有使用元素<form>。从技术上讲,那个按钮只是一个图像。每次单击该图像时,都会触发 send_data() 函数。

有人可以帮忙吗?对此,我真的非常感激。谢谢!

【问题讨论】:

  • 使用表单内容类型会更容易。或者只是不指定一个。或者让你的 python 服务器接受 OPTIONS 请求。
  • 您好,请问如何让服务器接受 OPTIONS 请求?我是否将 method='POST' 更改为 method='OPTIONS'?对不起,我是个新手……
  • 表单仍然使用 POST,OPTIONS 由浏览器内部发送,用于非标准表单类型,以确保 CORS 功能。您可以使用普通表单标签在没有 CORS 的情况下发布,但您无法从中获得反馈。阅读“启用 cors”;那里有很多,我不知道足够的 python 来编写一个 OPTION 处理程序(尽管我敢肯定它相当简单)
  • 感谢您为我指出方向:)。我要试试。
  • 请不要张贴文字截图。

标签: javascript python ajax json bottle


【解决方案1】:

跨域请求作为一种安全措施受到浏览器的限制。可以通过设置Access-Control-Allow-Origin 标头来克服这个问题。您可以使用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

然后用你的例子:

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

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

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

请注意,最好允许特定来源,而不是使用*

您可以阅读更多关于跨域资源共享 (CORS) here

【讨论】:

    【解决方案2】:

    您可以通过禁用跨域限制来完成这项工作。

    在 safari 上,打开开发面板,勾选禁用跨域限制,或使用 Firefox 等浏览器。

    【讨论】:

      猜你喜欢
      • 2015-07-30
      • 2020-07-07
      • 2014-05-20
      • 2014-01-31
      • 1970-01-01
      • 1970-01-01
      • 2020-02-20
      • 2015-06-22
      • 1970-01-01
      相关资源
      最近更新 更多