代码之家  ›  专栏  ›  技术社区  ›  bradley

通过XMLHttpRequest发送POST请求时,Flask返回400错误

  •  0
  • bradley  · 技术社区  · 2 年前

    我使用的是一个flask应用程序,每次发送POST请求时都会导致400 Bad request错误。请帮忙修理。

    我有一个烧瓶应用程序,它正在托管一个简单的网站。我为用户添加了使用网站编辑存储在服务器上的一些数据的功能。然后我遇到了一个问题,每次我点击按钮从服务器上删除列表项时,它发送的发布请求都会导致400个错误。这是通过从服务器请求数据,编辑数据,然后通过post请求将其发送回服务器来实现的。我很确定这是一个后端问题,因为我使用了开发人员工具来查看请求头,这对我来说很好。 以下是烧瓶应用程序中函数的代码:

    @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("")
    

    以下是请求的JavaScript代码:

    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();
            }
    
    1 回复  |  直到 2 年前
        1
  •  0
  •   Maxim    2 年前

    需要以FormData格式发送数据

    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();
    }