I'm working on a web app that involves a map. I'm trying to send the current map location from my index.js to the flask server for some processing. I receive a 400 bad POST request with the error
I've been thinking about this but have not been able to figure it out. Here is my Flask side code. Here you can see that it always excepts and the flask server receives an empty 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)
and this is the function where I try to send the location via 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);
}
});
}
I've used the Geolocation API here. This above function is called by the following line:
navigator.geolocation.getCurrentPosition(success, error, options);
I have tested the values with alerts, and it seems that the success is being triggered. I can't seem to figure out why this doesn't work though. I tried using data: {'data': posi} instead but it did not work.
Thanks!
Edit: I added an assignment of the variable 'data' in the except clause too, but it seems to default to that regardless.
If you examine what is getting passed in the body of the request, you will see that data is being converted to URL parameters (see below). You need to convert the data to a JSON string first. Next, the JSON of the request is not wrapped in an additional dict with 'data' as the only key. You also don't need the if block.
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)
Making a POST request with the following will error in the Python side:
$.ajax({
method: 'POST',
url: '/',
data: {'lat': 12.3, 'lon': 45.6},
contentType: 'application/json',
success: function(res){console.log(res);}
})
and the printed request.data gives the following:
b'lat=12.3&lon=45.6'
and the console log shows:
{'error': "<BadRequest '400: Bad Request'>"}
So you can see, the body of the ajax request is not proper JSON at all. To fix this we need to convert it to JSON before making the request using JSON.stringify
$.ajax({
method: 'POST',
url: '/',
data: JSON.stringify({'lat': 12.3, 'lon': 45.6}),
contentType: 'application/json',
success: function(res){console.log(res);}
})
and now the printed request.data gives what we want to see:
b'{"lat":12.3,"lon":45.6}'
and the console log shows what we expect as well:
{lat: 12.3, lon: 45.6}