Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

268
Vistas
Error 404 on a POST request from Ajax to Flask

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.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda