Axios post request with formData

Viewed 371

I want to make a form with multiple input (two text and one image). Furthermore, I'm using react, axios, formik and I submit my data to strapi.

With only one text and one file, it works fine, but when I try to add a new append, I've got the error

When using multipart/form-data you need to provide your data in a JSON 'data' field.
const onSubmit = async (event) => {
    const data = new FormData()

    //This works
    data.append('data', JSON.stringify({title:event.title}))      
    data.append('files.cover', file)

    //This doesnt
    data.append('title', JSON.stringify({title:event.title}))
    data.append('description', JSON.stringify({description:event.description}))
    data.append('files.cover', file)

       
       
    try{
        const response = await axios.post('http://localhost:1337/foodtrucks', data,  
            {                
                headers: userToken && { Authorization: `Bearer ${userToken}` }
            },
        )

        // const data = await response.json()

        console.log("response", response)

    } catch(err){           
        // setError(err.response.data.message[0].messages[0].message)
        setError("error")
        console.log(err)
    }
}

I tried to add headers, to use form-data, etc. Nothing works.

1 Answers

I think axios is meant for calling APIs - it may not be easy (or possible to send form data).

If you're running in the Browser, you may want to use plain XMLHttpRequest. I came across this article, which defines the submitForm function. It has helped me a lot on many projects.

Related