Dealing with multipart/form-data in Express using cloud functions in the upcoming year of 2022

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.

Answer №1

The Firebase Functions platform is built on a specialized version of the functions-framework-nodejs package. This variant includes functionality that automatically parses the request body before your code is executed, as detailed in this documentation.

As a result, attempting to feed the request's body stream directly into busboy will not work, leading to an "Unexpected end of form" error. To access the original request body, you must use the rawBody property provided by the framework.

This requires replacing the line:

busboy.end(req.body);

with:

busboy.end(req.rawBody);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing a jQuery variable within an .html() method

Can a Jquery if statement be used to display different content inside a div based on a variable? For example, if the variable is set to "cats", the displayed content might say "I like cats", and if it changes to "dogs", it would read "I like dogs". Is this ...

Utilizing the Composition Root concept in a TypeScript Express application

I am trying to grasp the concept of implementing a composition root in a project. Based on my research, improper usage of the composition root (such as referencing it in multiple places within your application code) can lead to the service locator antipat ...

Add the jquery files to an HTML document using Node.js

Below is the content of my index.html file: <html> <body> <script src="public/jquery-latest-min.js"></script> /*However, this script file is not importing and causing an error */ </body> </html& ...

When trying to pull a component from Svelte, I receive an error message stating "Selection Range

I'm still relatively new to svelte, so I might be handling things incorrectly. Whenever I attempt to separate my button component, regardless of whether I name the component ./Button.svelte, ./Button, Button.svelte, or try variations with capitalizat ...

Can you explain how to convert a 32-bit floating point number from a Buffer to a JSON string in NodeJS while maintaining the original precision?

Given a buffer with single precision float numbers (32 bits, little endian), the goal is to create a JSON string holding those numbers while maintaining their original values without any loss of precision. The challenge lies in the fact that when a value ...

What is the best way to consistently apply parent transforms to child elements in the same sequence?

Within my software, users have the ability to select 3D objects on a workplane and then scale, move, or rotate these elements collectively using a "transformation" container. This container, represented by an Object3D, groups all transformations and applie ...

Error message: "An issue occurred: Unable to access undefined properties (specifically, borderRadius) in MUI react."

I recently created a navigation bar with an integrated search bar component. The styling for my search component was done using MUI styled from @emotion/styled in MUI library, where I applied a borderRadius: theme.shape.borderRadius. However, I encountere ...

When attempting to debug JavaScript in Edge with Visual Studio Code, an error message stating 'Failed to load source map for chrome-error...' was encountered

Attempting to troubleshoot JavaScript code in Visual Studio Code is resulting in an error: Could not read source map for chrome-error://chromewebdata/: Unexpected 503 response from chrome-error://chromewebdata/edge-elixir-neterror.rollup.js.map: Unsupporte ...

Is it necessary to include "import { createServer } from 'http';" in order to utilize the websockets/ws library with Express in Node.js?

After encountering an issue with my working express server, I attempted to add websockets functionality using the following code: import express from "express"; import { WebSocketServer } from 'ws'; const app = express(); const port = 8 ...

Inquiry about Date and Time Selection Tool

I am working on a PHP project that includes two textboxes: one for selecting dates and the other for choosing a specific time. What I need assistance with is disabling any times before the selected date in the second timepicker textbox if today's dat ...

Exploring the concepts of AngularJS directives and resources

I've been experimenting with angularjs and rest service calls to display specific data sets, but I'm encountering challenges with custom directives and resources. Currently, I have a custom directive that loads a list of comments in an applicati ...

I am looking to personalize a Material UI button within a class component using TypeScript in Material UI v4. Can you provide guidance on how to achieve this customization?

const styling = { base: { background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)', border: 0, borderRadius: 3, boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)', color: 'white', height: 48, ...

Ways to troubleshoot and resolve the jQuery error with the message "TypeError: 'click' called"

I am currently developing a project for managing Minecraft servers, focusing on a configuration panel. I have set up a form that users need to fill out in order to configure the settings and send the values using Ajax. However, I encountered an error: Type ...

Is the utilization of react-router for developing 'single-page applications' causing a depletion of server resources?

Hello, I am relatively new to the world of web development and would appreciate guidance on any misunderstandings I may have. Currently, I am immersing myself in learning the MERN stack. For my practice project, I am aiming to create a simple two-page webs ...

Exploring the features of mobile search criteria filtration in jQuery

I have a homepage with various criteria that users can select such as budget maximum and minimum. When they click on the "search" button, I want it to lead them to a list of links on another page that corresponds to their search using jQuery Mobile and ...

Tips for dynamically adjusting an iframe's content size as the browser window is resized

Currently, I am in the process of building a website that will showcase a location on a map (not Google Maps). To achieve this, I have utilized an iframe to contain the map and my goal is for the map to adjust its width based on the width of the browser wi ...

Combining td elements within a table

Currently, I am working on creating a weekly calendar using a combination of JavaScript and PHP to interact with an SQL table. The process involves generating an empty table structure in JavaScript and then populating specific cells with data retrieved fro ...

Encountered unexpected character error while parsing JSON data

I am encountering the following error message: JSON.parse: unexpected character when I execute this code in firebug: JSON.parse({"balance":0,"count":0,"time":1323973673061,"firstname":"howard","userId":5383,"localid":1,"freeExpiration":0,"status":fals ...

Locating the dot character within regular expression challenges

Having difficulty replacing terms like "joe." using a regular expression. Look at the snippet below: var phrases = new Array("joe","sam"); sentence = "joe.id was here as well as sam.id"; for(i = 0; i < phrases.length; i++) { regex = new RegEx ...

Adjust the height of a div in JQuery to fit new content after specifying a height previously

I have a division element with an initial height of 0 and opacity set to zero, its overflow is hidden, and it contains some content. <div style='height: 0px; opacity: 0px; display: none; overflow: hidden; border: 1px solid #000;' id='myd ...