Access file upload formData in Express

Viewed 6102

How can I access the files in the API?

I read the other solutions and all of them require npm packages to solve this. I want to understand why I can't do it vanilla. Also, the answers are old and recommend using body-parser, which now comes bundled with Express.

I would like the solution to be vanilla JS in order to understand the process better.

client

async function uploadFile(file) {
    let formData = new FormData();
    formData.append("file", file);

    let res = await fetchPostFile("/api/files", formData);
}

fetch

export async function fetchPostFile(url, formData) {
    try {
        let result = await (
            await fetch(url, {
                method: "POST",
                withCredentials: true,
                credentials: "include",
                headers: {
                    Authorization: localStorage.getItem("token"),
                    Accept: "application/json",
                    "Content-type": "multipart/form-data",
                },
                body: formData,
            })
        ).json();

        return result;
    } catch (err) {
        return err;
    }
}

api

router.post("/api/files", async function (req, res, next) {
    try {
        console.log(req.file);          // undefined
        console.log(req.files);         // undefined
        console.log(req.body);          // {}

    } catch (err) {
        next(err);
    } finally {
        req.connection.release();
    }
});

Why is the req.body empty? Please help me understand what I'm doing wrong.

1 Answers

First you need to use multer package to handle multipart/form-data in express. You must use it as a middleware to set the field name for the file. The name passed as an argument to the single() function must match to the appended name on client side.

const multer = require('multer')

router.post("/api/files", multer().single('file'), async function (req, res, next) {
  try {
      console.log(req.file)
  } catch (err) {
      next(err)
  } finally {
      req.connection.release()
  }
});
Related