我正在尝试向一个瓶子服务器发送一个POST AJAX请求并读取查询字符串参数。 这对GET方法有效,但对POST,bottle.request.query\u字符串是空的。你知道吗
这是在python3.6.8中实现的。0.12.17中的瓶子版本
我卡住了,请告诉我。你知道吗
瓶子服务器:
#!/usr/bin/env python3
import bottle
print(bottle.__version__)
class EnableCors(object):
name = "enable_cors"
api = 2
def apply(self, fn, context):
def _enable_cors(*args, **kwargs):
bottle.response.headers["Access-Control-Allow-Origin"] = "*"
bottle.response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, OPTIONS"
bottle.response.headers["Access-Control-Allow-Headers"] = "Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token"
if bottle.request.method != "OPTIONS":
return fn(*args, **kwargs)
return _enable_cors
application = bottle.app()
application.install(EnableCors())
@application.route("/api/params", method=['OPTIONS', 'POST'])
def Api_Params():
print('bottle.request.query_string:', bottle.request.query_string)
bottle.run(host='0.0.0.0', port=8080, debug=True, reloader=True)
测试脚本客户端:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<script>
function test_post_param() {
var data = {'e': 'E', 'f': 'F', 'g': {'aa':'AA', 'bb':'BB'}};
$.ajax({
url: 'http://127.0.0.1:8080/api/params',
method: "POST",
data: "key=a",
// contentType: "text/plain",
success: function (response, textStatus) {
console.debug("test_post_param OK");
console.debug(textStatus);
console.debug(response);
},
error: function (response, textStatus) {
console.debug("test_post_param ERR");
console.debug(textStatus);
console.debug(response);
},
})
}
window.onload = test_post_param;
</script>
</body>
</html>
我把它放在我所有的API端点上。我将POST表单和查询编码组合成一个dict
所以您的代码如下所示:
下面是一个将数据作为JSON发送到POST路由的示例,我已经成功地使用了它。你知道吗
JQuery AJAX调用:
瓶子路径:
我更喜欢
from bottle import route, get, post, template, static_file, request
作为import语句。这使得路线写得更简单(在我看来)。你知道吗相关问题 更多 >
编程相关推荐