Trying to make a XMLHttpRequest POST to my flask app but I keep getting 400 error

36 views Asked by At

This is my flask app

from flask import Flask, render_template, request, jsonify 
from flask_cors import CORS


app = Flask(__name__) 
CORS(app)

@app.route("/") 
def hello(): 
    return render_template('index.html') 


@app.route('/process', methods=['POST']) 
def process(): 
    data = request.get_json() # retrieve the data sent from JavaScript 
    print("data")
    # process the data using Python code 
    result = data['value'] * 2
    return jsonify(result=result) # return the result to JavaScript 

if __name__ == '__main__': 
    app.run(debug=False) 

This is my js code, originally I was using jquery, but it wasnt working with cors so I switched to using XMLHttpRequest as suggested by another post, which fixed the cors error but now i have a 400 bad request error

function submit_clicked() {
    var info = document.getElementsByClassName("info")
    var title = document.getElementById("title").innerText
    console.log(title);
    if (title ==  "Create User Account") {
        const data = {
            "Firstname" : info[0].value,
            "Lastname" : info[1].value,
            "Username" : info[2].value,
            "Email" : info[3].value,
            "Password" : info[4].value,
            "Retype_Password" : info[5].value
        }
        sendData(data)
    }
}
function sendData(data) { 
    const xhr = new XMLHttpRequest();
    xhr.open("POST", "http://127.0.0.1:5000/process"),
    xhr.send(JSON.stringify({ 'value': "value" })),
    xhr.onreadystatechange = function() { 
        if (xhr.readyState === 4 && xhr.status >= 400) { 
          console.log(xhr.response)
        } else { 
          //success 
        } 
    }
}

This is the error I get in the console of chrome when I try debug

I was trying to send the details stored in the var data to the flask app

0

There are 0 answers