Seeking advice on handling multipart/form-data requests in an Express backend with Google Cloud Functions in 2022. Despite numerous attempts, the issue remains unresolved after extensive research and testing various methods that work locally but fail when deployed.
The code functions properly locally but encounters errors when deployed:
- Unexpected end of form error occurs during deployment
- Error message 'Busboy is not a constructor' is resolved by removing new BusBoy but reverts to former error
// Code snippets for processing multipart/form-data files middleware
// [Code removed for brevity]
How do seasoned professionals tackle this challenge? Any insights would be appreciated.
edit 1 The error
node:events:505 throw er;
// Unhandled 'error' event ^ Error: Unexpected end of form at Multipart._final (functions/node_modules/busboy/lib/types/multipart.js:588:17) at callFinal (node:internal/streams/writable:695:27) at prefinish
(node:internal/streams/writable:724:7) at finishMaybe
(node:internal/streams/writable:734:5) at Multipart.Writable.end
(node:internal/streams/writable:632:5)
The frontend sending the request includes the following code:
const API_URL = "http://192.168.1.2:4000/api/admissionForm/submit";
const uploadFile = async (file: any) => {
const token = JSON.parse(sessionStorage.getItem("user") || "{}").token;
try {
const config = {
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "multipart/form-data",
},
};
const res = await axios.post(API_URL, file, config);
return res.data;
} catch (err: any) {
if (err.response.status === 500) {
console.log("There was a problem with the server");
} else {
console.log(err.response.data.msg);
}
}
};
HTML section:
<form onSubmit={handleUpload}>
<input
type="file"
className=""
id="inputFile01"
style={{ visibility: "hidden" }}
onChange={changeHandler}
name={"file"}
/>
<button type="submit">
Upload
</button>
</form>
Code for changeHandler()
:
const changeHandler = (e: SyntheticEvent) => {
const target = e.target as HTMLInputElement;
let selectedList = target.files as FileList;
let selected = selectedList[0] as File;
setFile(selected);
};
const handleUpload = async (e: SyntheticEvent) => {
e.preventDefault();
if (file) {
const formData = new FormData();
formData.append("file", file);
try {
const res = await uploadFile(formData);
} catch (error) {
console.log(error);
}
}
};
Some reports indicate this is a recurring issue with Cloud Functions, although older threads suggest it has been addressed. Seeking solutions for Oct 2022.