-1

I'm trying to make POST requests through Nodejs to flask. When I do so, Flask thinks the request.form dictionary is empty. Here is the flask code:

@app.route("/join_game/join/desktop", methods=["POST"])
def join_game_post_desktop():
    print("Hi", request.form.get("gameid"), flush=True)
    id = request.form.get("gameid")
    try:
        if games[int(id)] != None:
                return jsonify({"success":True, "gameid":id})
    except IndexError:
        pass
    return jsonify({"success":False})

Here is the Nodejs (electron) code:

    const data = JSON.stringify({
      gameid:document.querySelector("#gameid").value
    });

    const options = {
      host:domain,
      port:5000,
      path:"/join_game/join/desktop",
      method:"POST",
      headers:{
        "Content-Type":"application/json",
        "Content-Length":Buffer.byteLength(data)
      }
    };

    const request = http.request(options, (response) => {
      let data = "";

      response.on("data", (chunk) => {
        data+=chunk;
      });

      response.on("end", () => {
        console.log(data);
      });
    });

    request.write(data);
    console.log(data);
    request.end();

What is the issue?

Serket
  • 3,785
  • 3
  • 14
  • 45

1 Answers1

1

Since you are using "Content-Type":"application/json" Flask will consider this POST as a json request.
See https://flask.palletsprojects.com/en/1.1.x/api/#flask.Request.get_json
so all need to do is to use to call request.get_json()

balderman
  • 22,927
  • 7
  • 34
  • 52