javascript - 将 json 数据 POST 到 Bottle

标签 javascript python ajax json bottle

我是 Bottle 的新手,也是 Python 的新手,每当我单击按钮时,我都会尝试创建一个应用程序,触发 AJAX 并将 json POST 到服务器并使用 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()函数被触发。

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

最佳答案

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

关于javascript - 将 json 数据 POST 到 Bottle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27352485/

相关文章:

php - 两次单击以填充表单

javascript - 每 x 秒播放一次声音(循环)

javascript - Typescript 类型转换现有变量

javascript - 为什么 Chrome 开发者工具不显示所有 JavaScript 文件?

python - Python : Handling requests exceptions the right way

javascript - Polymer iron-ajax 绑定(bind)值到重复模板中的纸项

JavaScript数据访问设计

python - 如何在 PySide/PyQt 中设置 "read-only checkbox"

python - 如何在python中只获取文件?

javascript - Ajax 新手,尝试在 div 中加载另一个页面,但在 Safari 中遇到问题