Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

266
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda