NodeJs with Express not parsing form data from node-fetch

Viewed 368

I'm creating two APIs with NodeJS, Express, and TypeScript. One API will take a request with a content type of multipart/form-data, and will use the body in the request to make another request to a second API.

I'm using Postman, so the chain of request looks something like this

Postman -> First API -> Second API

I use node-fetch to make a request from the first API to the second one. The body of the request is a FormData, which contains some files and key-value pairs.

    const form = new FormData();
    
    // File for profile picture
    const profilePictureBuffer = await (await fetch(user.profilePicture)).buffer();
    form.append('profilePicture', profilePictureBuffer);

    // File for ID Card
    const idCardBuffer = await (await fetch(user.idCardUrl)).buffer();
    form.append('idCard', idCardBuffer);


    // This part iterats over the obsect of 'user',
    // which contains other key-value pairs
    Object.entries(user).forEach((data) => {
        form.append(data[0], data[1]);
    });

    // Make POST request to second API
    const pinterUser = await fetch(secondAPIURL, {
        method: 'post',
        body: form,
        headers: form.getHeaders()
    });

I ran both of the APIs on localhost so that I can monitor the logs for any bugs. As I make a request from Postman to the first API, then the first API make another request to the second API, I got the following error log in the terminal for the second API

TypeError: Cannot read property '0' of undefined

After some investigation, I found out that, in the second API, the req.body and req.files are empty objects. This means that Express did not parse the incoming request. Note that I've also already a multer middleware to handle the files in the request.

Furthermore, I have added the following lines of code in my server.ts file for the second API

/** Parse the body of the request */
router.use(express.urlencoded({ extended: true }));
router.use(express.json());

However, when I tried making the request from Postman, it returns a successful response.

I'm not really sure what's going on here. I've tried looking for some answer regarding this similar issue, but most of them suggest adding urlencoded and json, or using some other library to handle parsing form data.

In my case, the first suggestion doesn't solve my problem since I already added them from the start, and the latter is what I'm trying to avoid.

I wonder if anybody could point out what I was missing here? Thanks in advance

0 Answers
Related