首页 > 解决方案 > 为什么这段代码中的 axios 没有向 Vue 中的后端发送任何数据?

问题描述

我正在尝试使用 Vue js 将图像上传到服务器,但听起来 Axios 没有向后端发送任何数据。后端是 ASP.netCore API。这非常简单,我之前已经制作了这个表单,用于通过 fetch 向服务器提交数据,并且效果很好!你看有什么不对吗?你可以在下面看到我的代码:

 <template>
    <h1>Uploading an Image!</h1>
    <p>This component demonstrates Uploading Image to server.</p>
    <div>
        <form>
            <input type="file" v-on:change="getFile($event)" />
            <button v-on:click="submitForm($event)">Upload</button>
        </form>
    </div>
</template>

<script>
    import axios from 'axios'

    export default {

        name: "Upload1",
        data() {
            return {
                selectedFile: " ",
                uploadResult: " "
            }
        },

        methods: {

            getFile(event) {
                this.selectedFile = event.target.files[0];
                console.log(this.file);
            },

            submitForm(event) {
                event.preventDefault();
                let formData = new FormData();
                formData.append("ImageData.File", this.selectedFile);

                let config = {
                    headers: {
                        "Content-Type": "multipart/form-data"
                    }
                };
                axios.post('/api/Image', {

                    formData,
                    config

                }).then(resposne => resposne.json())
                    .then(data => {
                        console.log(data);
                        
                        this.uploadResult = "File " + data.fileName + " successfully uploaded."
                    });
            }
        }

    };

</script>

标签: javascriptvue.jsvuejs3

解决方案


我将 formData 和 config 包装在一个对象中。它们应该是传递给 post 的第二个和第三个参数,如下所示:

axios.post('/api/Image', formData, config)

并且问题解决了!


推荐阅读