我是 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/