I'm trying to send a new FormData() as the body of a POST request using axios and Multer to handle multipart form data, locally it works without any issues but on our live envs I keep getting Unexpected end of form at .callFinal
. The content-type seems to be the expected multipart/form-data
with the set boundary. But it still this gives this error. I've found similar threads on stackoverflow, this one was the closest to mine: Unexpected end of form error when using Multer but none of the answeres seemed to solve the issue for me. (I haven't tried downgrading as I don't think that would be the main issue here)
I've tried:
- Setting the header manually but when not setting it defaults back to the correct
multipart/form-data
- Adding
bodyParser.json({extended:true})
before the multer middleware - Removing bodyParser.json() from express level
- Switching the middleware to
express-fileupload
- Switching up the order of the Form Data items to have file at the end
- Using different HTTP clients to send the request
But still getting the same error. Any ideas on what can cause this?
I'm on Multer version: 1.4.5-lts.1
This is the api call:
export const uploadFiles = async {
formData: FormData;
groupId:string
) => {
try {
const res = await axios({
method: "post",
url: `${EnvironmentUtils.getBaseUrl()}/files/upload`,
params: {
groupId,
},
data: formData,
headers: {
ApiKey: EnvironmentUtils.getApiKey(),
},
withCredentials: true,
} catch (err) {
const publicErrMsg = err?.response?.data?.message;
throw new Error(
`Error when uploading file: ${publicErrMsg || err.message}`,
);
}
};
This is where data being appended to formData:
const upload = useCallback(
async (files: FileList) => {
const formData = new FormData();
formData.append("filesData", files[0]);
formData.append("folderPath", btoa(selectedFolderPath || ""));
formData.append("friendlyName", files[0].name);
try {
const res = await uploadFiles(
formData,
groupId
);
And on the backend the middleware is:
export const upload = Multer({
storage: Multer.memoryStorage(),
limits: {
fileSize:
FirebaseUtils.getEnvironmentVar("multer.max.file_size") ||
10 * 1024 * 1024, // No larger than 10mb
fieldSize:
FirebaseUtils.getEnvironmentVar("multer.max.field_size") ||
10 * 1024 * 1024, // No larger than 10mb
},
});
Router:
app.post(
"/files/upload",
authManager,
MulterMiddleware.upload.single("filesData"),
Controller.handlePostFileUploads,
);
And then getting the file data from req.file
in handlePostFileUploads
like this:
export const handlePostFileUploads: RequestHandler = async (req, res) => {
const groupId = req.groupId!;
const file = req.file;
const { folderPath, friendlyName } = req.body; // Can this be the issue?
I think the issue probably lies somewhere on the Multer middleware side but I'm not exactly sure what I'm missing
In my server I have the following set:
Server.js
const express = require("express")();
express.use(bodyParser.json());
There might be a collision between bodyParser and multer here?