I am using a flask app and a POST request causes a 400 Bad Request error every time it is sent. Please help fix it.
I have a flask app that is hosting a simple website. I was adding functionality for a user to use a website to edit some data stored on the server. Then I ran into a problem where every time I clicked a button to delete a list item from the server, the post request it sent caused 400 errors. This works by requesting the data from the server, editing the data, then sending it back to the server via a post request. I am pretty sure that this is a backend problem because I have used developer tools to look at the request headers and it looks good to me.
Here is the code for the function in the flask app:
@app.route("/orders", methods=["POST", "GET"])
def order():
global orders
newOrder(request.form["json"])
if request.method == "GET": #other functionality for GET requests
return(render_template("orders.html", orders=orders))
elif request.form["json"] != "": #what I added - when I access request.form["json"], it throws the error, and yes, I did remember to import request from flask
orders = json.loads(unquote(request.form["json"]))
return("")
and here is the JavaScript code for the request:
function del(e) { // What this function should do is delete a item from a server side list
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function () {
var json = JSON.parse(this.responseText);
var newJson = [] // Change the JSON Data
for (var i = 0; i < json.length; i++) {
if (json[i]["name"] != e.parentElement.childNodes[2]) newJson.push(json[i]); // Change the JSON Data
}
const xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/orders");
xmlhttp.send("json=" + encodeURI(JSON.stringify(newJson))); // Send it back
}
xmlhttp.open("GET", "/json"); // Request the JSON Data
xmlhttp.send();
}
>Solution :
Need to send data in FormData format
function del(e) {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function () {
var json = JSON.parse(this.responseText);
var newJson = []
for (var i = 0; i < json.length; i++) {
if (json[i]["name"] != e.parentElement.childNodes[2]) newJson.push(json[i]);
}
const xmlhttpPost = new XMLHttpRequest();
xmlhttpPost.open("POST", "/orders");
var formData = new FormData(); // <-- create FormData object
formData.append("json", JSON.stringify(newJson)); // <-- add json data to formData
xmlhttpPost.send(formData); // <-- send formData
}
xmlhttp.open("GET", "/json");
xmlhttp.send();
}