Flask giving 400 Bad Request On Sending File from React via form

Viewed 22

I am sending a form from React Frontend to Flask Backend. The React Code Snippet is as follows:

formdata.append("dataset", dataset);
    formdata.append("file_details", file_data);
    formdata.append("project_name", data);
    formdata.append("metadata", {});
    console.log(formdata);
    fetch(URL, {
      method: "POST",
      body: formdata,
      headers: { "Content-Type": "multipart/form-data" },
    }).then((response) => {
      if (response.ok) {
        console.log("It Worked");
        console.log(response.json());
      } else {
        console.log("It Failed");
        console.log(response.json());
      }
    });
  };

<input
            type="file"
            name="dataset"
            id="dataset"
            accept=".xlsx, .csv"
            onChange={(e) => {
              setDataset(e.target.files[0]);
            }}
            className="CreateProjectFormItemValue"
            required
          />

However, The flask backend is throwing a 400 Error (screenshot attached for reference): Flask Response. The error says

Bad Request: Did not attempt to load JSON data because the request Content-Type was not 'application/json'.

I am also attaching the code snippet for the flask endpoint handling the file upload.

@project_controller.route("/create", methods=["POST"])
def create_project():
    params = QueryParams(**request.json)
    params.validate_mandatory_fields(["project_name"])
    try:
        try:
            print("Attempting to save file")
            f = request.files['file']
            f.save(secure_filename(f.filename))
            print("File Saved Successfully")
        except Exception as ex:
            print(f"Failed to Upload File : {ex}")
        project_service.create_project(
            params.user_id, params.project_name, params.metadata
        )
        return make_response(jsonify({"message": "Project Created Successfully"}), 200)
    except Exception as ex:
        logger.error(ex)
        return make_response(
            jsonify({"message": f"Project Creation Failed", "Exception": ex}), 403
        )

Please let me know the issue and how do I fix it, so that Flask is accepting API calls where 'application/json' is not the content-type.

0 Answers
Related