I have a form inside a frontend which takes a file as an input along with 2 other variables.
<Form>
<Form.Group className="mb-3">
<Form.Check
type="switch"
id="ipfs-switch"
label="Add Images to IPFS"
onChange={ifpsChange}
/>
<Form.Check
type="switch"
id="cdn-switch"
label="Add Images to Image Kit(CDN)"
onChange={imgKitChange}
/>
<Form.Control type="file" onChange={changeHandler} />
</Form.Group>
<Form.Text id="passwordHelpBlock" muted>
You should choose a excel sheet with a single sheet and all the correct columns.
</Form.Text>
</Form>
The inputs are set into states using these methods.
const changeHandler = (event) => {
setSelectedFile(event.target.files[0]);
};
const ifpsChange = (e) => {
setIpfsBool(e.target.value);
};
const imgKitChange = (e) => {
setImgBool(e.target.value);
};
When the form is submitted I upload the file and other values for processing by a API also written by me. I use fetch to do this.
const uploadMetaData = (e) => {
console.log(typeof(ipfsBool));
console.log(typeof(imgBool));
console.log(typeof(pannel));
console.log(typeof(selectedFile));
setIsLoading(true);
const sc = process.env.REACT_APP_FAST_KEY;
let formData = new FormData();
formData.append("file", selectedFile);
formData.append("ipfs", ipfsBool);
formData.append("image_kit", imgBool);
formData.append("city", pannel);
fetch("https://pythonapi.metropolisworld.io/addCitydata", {
method: "POST",
headers: {
"Content-Type": "multipart/form-data",
secretkey: sc,
},
body: formData,
})
.then((response) => response.json())
.then((result) => {
console.log("Success:", result['detail']);
})
.then((response) => {
setIsLoading(false);
})
.catch((error) => {
console.error("Error:", error);
setIsLoading(false);
});
};
I know the API is working as expected because when I call it from postman it works fine. However when I call it from the frontend using the above I get and error.
[Error] Failed to load resource: the server responded with a status of 400 () (addCitydata, line 0)
the print out of the result gives me the following.
[Log] Success: – "There was an error parsing the body"
Can anyone suggest what I am missing here?
In the end the answer was a simple as removing the "Content-Type":
header. It turns out fetch automatically sets that in the background, so by overriding it I caused the error.