Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to send text and formData in one fetch call

I am trying to send text and formData in one fetch call to a Node.js backend using multer.

I can send formData on its own with no issues, but when I try and add text, the api call stays ‘pending’.

Here is my fetch call that works just with formData:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  const handleImage = async (e) => {
    var formData = new FormData();
    let file = e.target.files[0];

    formData.append("image", file);

    try {
      const upload = await fetch(
        `${process.env.NEXT_PUBLIC_SERVER_API}/uploadImage`,
        {
          method: "POST",
          body: formData,
        }
      );
    } catch (e) {
      console.log("Something went wrong!");
    }
  };

Here is the same fetch call with text added that does not work:

const handleImage = async (e) => {
    var formData = new FormData();
    let file = e.target.files[0];

    formData.append("image", file);

    try {
      const upload = await fetch(
        `${process.env.NEXT_PUBLIC_SERVER_API}/uploadImage`,
        {
          method: "POST",
          body: {formData, userId}
        }
      );
    } catch (e) {
      console.log("Something went wrong!");
    }
  };

It also doesn’t work if I try and user JSON.stringify().

>Solution :

I do believe that you can’t send a formData and json body at the same time (maybe there is a way somehow i don’t know)
because multer will just take the file from formdata and the other property will be set to req.body so if you want to send userId you can try

const handleImage = async (e) => {
    var formData = new FormData();
    let file = e.target.files[0];

    formData.append("image", file);
    formData.append("userId", userId);

    try {
      const upload = await fetch(
        `${process.env.NEXT_PUBLIC_SERVER_API}/uploadImage`,
        {
          method: "POST",
          body: formData,
        }
      );
    } catch (e) {
      console.log("Something went wrong!");
    }
  };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading