I make form upload image in Reactjs by fetch but don't work

Viewed 20

hello everybody I make form upload image in Reactjs by fetch but don't work

POST http://localhost:5000/api/product/new 500 (Internal Server Error) Error: SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

export const ValidationSchemaExample = () => {
   let send = event => {
    event.preventDefault();
    console.log(event.target );
    const formData = new FormData(event.target);
    
    fetch('http://localhost:5000/api/product/new', {
        method: 'POST', 
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        body: formData 
      })
      .then((response) => response.json())
      //Then with the data from the response in JSON...
      .then((data) => {
        console.log('Success:', data);
        // window.location='/';
      })
      .catch((error) => {
        console.error('Error:', error);
      }); 

    }
    return (

        <div>
            <h1>admin/project </h1>

            <form  onSubmit={ send} method="post" >

                <input name="name" placeholder='Enter your name' />
                <input name="price" type="price" placeholder='Enter your price' />
                <input name="category" type="category" placeholder='Enter your category' />
                <input name="minimumQuantity" type="discountRate" placeholder='Enter your minimumQuantity' />
                <input name="discountRate" type="discountRate" placeholder='Enter your discountRate' />
                <input name="image" type="file" placeholder='Enter your image' />
                <button type="submit">Submit</button>
            </form>

        </div>
    )
};
1 Answers

You have to append each field value using .append method like this

const formdata = new FormData(); formdata.append('name', data.name); formdata.append('price', data.price);

Related