【问题标题】:Axios post request with formDataAxios 使用 formData 发布请求
【发布时间】:2021-09-01 19:38:38
【问题描述】:

我想制作一个具有多个输入(两个文本和一个图像)的表单。 此外,我正在使用 react、axios、formik 并将我的数据提交给strapi。

只有一个文本和一个文件,它工作正常,但是当我尝试添加一个新的附加时,我得到了错误

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)
    }
}

我尝试添加标题、使用表单数据等。没有任何效果。

【问题讨论】:

    标签: reactjs axios formik strapi


    【解决方案1】:

    我认为 axios 是用来调用 API 的——它可能并不容易(或者不可能发送表单数据)。

    如果您在浏览器中运行,您可能希望使用纯 XMLHttpRequest。我遇到了this article,它定义了submitForm 函数。它在许多项目中帮助了我很多。

    【讨论】:

    • 我认为this article 可以帮助你。 使用 axios 在 POST multipart/form-data 请求中发送文件和 json
    • 我仍然收到此错误“使用 multipart/form-data 时,您需要在 JSON 'data' 字段中提供数据。”
    • 我找到了一个解决方案,但它并不干净,它可以工作:data.append('data', JSON.stringify({title:event.title, description:event.description}))
    猜你喜欢
    • 2018-03-22
    • 1970-01-01
    • 2021-08-24
    • 2022-12-10
    • 2018-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    相关资源
    最近更新 更多