【问题标题】:Try to upload file with axios post request尝试使用 axios post 请求上传文件
【发布时间】:2021-12-19 04:42:28
【问题描述】:

我正在尝试使用以下代码通过axios.post 请求上传文件:

export const create = (data) => {
    api.post("/api/v1/redacao", { tema: data.tema }).then(postResponse => {
        const resp = api.patch("/api/v1/redacao/" + postResponse.data.redacao.id, { titulo: data.titulo, texto: data.conteudo }).then(patchResponse => {
            if (patchResponse.status === 200) {
                if (data.file) {
                    const formData = new FormData();
                    formData.append('file', data.file)
                    const config = {
                        headers: {
                            'content-type': 'multipart/form-data'
                        }
                    }
                    return api.post("/api/v1/redacao/uploadRedacao/" + postResponse.data.redacao.id, formData, config)
                }
                return false;
            }
            return null
        })
        if (resp) {
            resp.then((response) => { console.log(response) })
        }
        return false;
    })
}

但是当我在 Chrome 开发工具中查看有效负载数据时,有效负载是空的。 如果我使用没有链接的发布请求,则请求可以正常工作。

有人知道 FormData 有什么问题吗?

【问题讨论】:

标签: javascript reactjs axios


【解决方案1】:

我创建了一个模块调用 api,它创建了一个 axios 实例,我使用它是因为授权标头、baseUrls 和拦截器。我再次导入 axios 并创建其他实例来发出这个特定请求,并且它现在可以工作了

export const create = (data) => {
api.post("/api/v1/redacao", { tema: data.tema }).then(postResponse => {
    if (data.file) {
        let formData = new FormData()
        formData.append('file', data.file)
        buildUploadFileHeader().then(headers => {
            axios.post(REACT_APP_BACKEND_URL + '/api/v1/redacao/uploadRedacao/' + postResponse.data.redacao.id, formData, { headers }).then(uploadResponse => {
                if (uploadResponse.status === 201) {
                    return false
                }
            })
        })
    }
    else {
        api.patch("/api/v1/redacao/" + postResponse.data.redacao.id, { titulo: data.titulo, texto: data.conteudo }).then(patchResponse => {
            if (patchResponse.status === 200) {
                return false;
            }
            return null
        })
    }
    return true;
})

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-16
    • 2017-11-20
    • 2021-08-10
    • 2022-07-24
    • 2016-11-15
    • 1970-01-01
    • 2020-06-16
    • 2017-12-08
    相关资源
    最近更新 更多