我正在开发一个涉及地图的网络应用程序。我正在尝试将当前的地图位置从我的index.js发送到烧瓶服务器进行一些处理。我收到了400个错误的帖子请求
我一直在想这件事,但一直没能弄清楚。这是我的酒瓶侧码。在这里,您可以看到它总是例外,而烧瓶服务器接收到一个空的dict:
from flask import Flask, render_template, request
app = Flask(__name__, template_folder='templates')
@app.route('/', methods=["GET"])
def index():
return render_template("index.html")
@app.route('/', methods=["POST"])
def post():
if request.method == 'POST':
try:
data = request.json['data']
print(data)
except Exception as e:
data = {}
print(e)
return data
if __name__ == "__main__":
app.run(debug=True)
这就是我试图通过ajax发送位置的函数:
function success(pos){
const posi = {
lat: (pos.coords.latitude),
lng: (pos.coords.longitude),
};
alert(posi.lat)
$.ajax({
method : "POST",
url : "/",
data: posi,
contentType: 'application/json',
success: function(result) {
alert("yay");
},error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
}
我在这里使用了地理定位API。上面的函数由以下行调用:
navigator.geolocation.getCurrentPosition(success, error, options);
我已经用警报测试了这些值,并且似乎已经触发了成功。但我似乎不明白为什么这不管用。我试着使用data: {'data': posi}
,但是它没有起作用。
谢谢!
编辑:我也在but子句中添加了变量'data‘的赋值,但不管怎么说,它似乎都是默认的。
发布于 2022-07-08 09:13:17
如果您检查请求正文中传递的内容,您将看到data
正在被转换为URL参数(参见下面)。您需要首先将数据转换为JSON字符串。接下来,请求的JSON不被包装在附加的dict中,'data'
是惟一的键。您也不需要if
块。
from flask import Flask, render_template, request
app = Flask(__name__, template_folder='templates')
@app.route('/', methods=["GET"])
def index():
return render_template("index.html")
@app.route('/', methods=["POST"])
def post():
print(request.data)
try:
data = request.json
except Exception as e:
data = {'error': repr(e)}
return data
if __name__ == "__main__":
app.run(debug=True)
使用以下内容发出POST请求将在Python方面出错:
$.ajax({
method: 'POST',
url: '/',
data: {'lat': 12.3, 'lon': 45.6},
contentType: 'application/json',
success: function(res){console.log(res);}
})
打印的request.data
提供了以下内容:
b'lat=12.3&lon=45.6'
控制台日志显示:
{'error': "<BadRequest '400: Bad Request'>"}
因此您可以看到,ajax请求的主体根本不是正确的JSON。要解决这个问题,我们需要在使用JSON.stringify
发出请求之前将其转换为JSON
$.ajax({
method: 'POST',
url: '/',
data: JSON.stringify({'lat': 12.3, 'lon': 45.6}),
contentType: 'application/json',
success: function(res){console.log(res);}
})
现在印刷的request.data
给出了我们想要看到的东西:
b'{"lat":12.3,"lon":45.6}'
控制台日志还显示了我们预期的内容:
{lat: 12.3, lon: 45.6}
https://stackoverflow.com/questions/72908106
复制相似问题