skip to Main Content

When I am trying to send form input data with an image to an API I am getting an Axios error 500 with message "Failed to parse multipart servlet request". before I was getting "company not found error because createdBy field was missing".

when I send new company data from Postman it’s successfully added.
inside body => form-data I have to pass 3 keys and value

keys        value
 logo    :   logo.png
 name    :   Abc Company
 company : {
           "websiteUrl":"www.abc.com",
           "firstName":"John",
           "lastName":"Doe",
           "emailId":"[email protected]",
           "phoneNumber":"1122334455",
           "createdBy":"110"
}

Is there anything wrong with my code or I am missing something ?

import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";

const AddCompany = () => {
  const [formData, setFormData] = useState({
    logo: null,
    name: "",
    company: {
      websiteUrl: "",
      firstName: "",
      lastName: "",
      email: "",
      phoneNumber: "",
      createdBy: "",
    },
  });

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prevState) => ({
      ...prevState,
      [name]: value,
    }));
  };

  // function to handle logo file input change
  const handleLogoChange = (e) => {
    setFormData((prevState) => ({
      ...prevState,
      logo: e.target.files[0],
    }));
  };

  // function to handle company info input changes
  const handleCompanyChange = (e) => {
    const { name, value } = e.target;
    setFormData((prevState) => ({
      ...prevState,
      company: {
        ...prevState.company,
        [name]: value,
      },
    }));
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(formData);
    const companyData = new FormData();
    companyData.append("logo", formData.logo);
    companyData.append("name", formData.name);
    companyData.append("websiteUrl", formData.company.websiteUrl);
    companyData.append("firstName", formData.company.firstName);
    companyData.append("lastName", formData.company.lastName);
    companyData.append("email", formData.company.email);
    companyData.append("phoneNumber", formData.company.phoneNumber);
    companyData.append("createdBy", formData.company.createdBy);

    axios
      .post(
        "http://localhost:8080/api/v1/company/create/company",
        companyData 
      )
      .then((response) => {
        console.log(response.data);
      })
      .catch((error) => {
        console.log(error);
      });
  };

  // Input Style ClassNames
  const inputClassName =
    "bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500";

  // label Class Names
  const labelClassNames =
    "block mb-2 text-sm font-medium text-gray-900 dark:text-white";

  return (
    <>
      {/* Form Section */}
      <form onSubmit={handleSubmit} encType="multipart/form-data">
        {/* Logo Section */}
        <div className="mb-5">
          <label className={labelClassNames} htmlFor="logo">
            Upload logo
            <span className=" text-blue-600"> (optional)</span>
          </label>
          <input
            className="block w-full text-sm text-gray-900 border border-gray-300 rounded-lg cursor-pointer bg-gray-50 dark:text-gray-400 focus:outline-none dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400"
            aria-describedby="file_input_help"
            type="file"
            onChange={handleLogoChange}
          />
          <p
            className="mt-1 text-sm text-gray-500 dark:text-gray-300"
            id="file_input_help"
          >
            SVG, PNG, JPG or GIF (MAX. 800x400px).
          </p>
        </div>
        <div className="grid gap-6 mb-6 md:grid-cols-2">
          <div>
            <label htmlFor="phone" className={labelClassNames}>
              Company Name
              <span className=" text-red-600"> (required)</span>
            </label>
            <input
              type="text"
              maxLength={150}
              name="name"
              value={formData.name}
              onChange={handleChange}
              className={inputClassName}
              placeholder="Company Name"

              // required
            />
          </div>
          <div>
            <label htmlFor="phone" className={labelClassNames}>
              Website URL
              <span className=" text-blue-600"> (optional)</span>
            </label>
            <input
              type="text"
              maxLength={100}
              className={inputClassName}
              placeholder="www.url.com"
              name="websiteUrl"
              value={formData.company.websiteUrl}
              onChange={handleCompanyChange}

              // required
            />
          </div>
          <div>
            <label htmlFor="first_name" className={labelClassNames}>
              Contact Person First Name
              <span className=" text-red-600"> (required)</span>
            </label>
            <input
              type="text"
              maxLength={50}
              className={inputClassName}
              placeholder="First name"
              name="firstName"
              value={formData.company.firstName}
              onChange={handleCompanyChange}
              // required
            />
          </div>
          <div>
            <label htmlFor="last_name" className={labelClassNames}>
              Contact Person Last Name
              <span className=" text-red-600"> (required)</span>
            </label>
            <input
              type="text"
              maxLength={50}
              className={inputClassName}
              placeholder="Last name"
              name="lastName"
              value={formData.company.lastName}
              onChange={handleCompanyChange}
              // required
            />
          </div>
          <div className="mb-6">
            <label htmlFor="email" className={labelClassNames}>
              Email address
              <span className=" text-red-600"> (required)</span>
            </label>
            <input
              type="email"
              maxLength={100}
              className={inputClassName}
              placeholder="[email protected]"
              name="email"
              value={formData.company.email}
              onChange={handleCompanyChange}
              // required
            />
          </div>
          <div className="mb-6">
            <label htmlFor="phone" className={labelClassNames}>
              Phone No
              <span className=" text-blue-600"> (optional)</span>
            </label>
            <input
              type="number"
              maxLength={50}
              className={inputClassName}
              placeholder="+1 123-456-789"
              name="phoneNumber"
              value={formData.company.phoneNumber}
              onChange={handleCompanyChange}
              // required
            />
          </div>
          <div className="mb-6">
            <label htmlFor="createdBy" className={labelClassNames}>
              createdBy
              <span className=" text-blue-600"> (optional)</span>
            </label>
            <input
              type="number"
              maxLength={50}
              className={inputClassName}
              placeholder="100"
              name="createdBy"
              value={formData.company.createdBy}
              onChange={handleCompanyChange}
              // required
            />
          </div>
        </div>
        <div className="flex justify-center">
          <button
            type="submit"
            className="text-white  bg-blue-700 hover:bg-blue-800 focus:ring-0 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm  w-60 px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"
          >
            Submit
          </button>
        </div>
      </form>
    </>
  );
};

export default AddCompany;

I would appreciate some help.

2

Answers


  1. It sounds like your API is expecting you to post an object with a property called "company". It’s hard to know without more information, but try something like this:

    const response = await axios.post(
            "http://localhost:8080/api/v1/company/create/company",
            {company: formData},
            {
              headers: { "Content-Type": "multipart/form-data" },
            }
          );
    
    Login or Signup to reply.
  2. I think you should send the form data like this.

      const handleSubmit = async (e) => {
        e.preventDefault();
        const formData = new FormData();
        formData.append("logo", logo);
        formData.append("name", name);
        formData.append("company", company);
        try {
          const response = await axios.post(
            "http://localhost:8080/api/v1/company/create/company",
            formData,
            {
              headers: { "Content-Type": "multipart/form-data" },
            }
          );
          console.log(response.data);
          navigate("/company");
        } catch (error) {
          console.log(error);
        }
      };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search