javascript - 为什么这段代码中的 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>
解决方案
我将 formData 和 config 包装在一个对象中。它们应该是传递给 post 的第二个和第三个参数,如下所示:
axios.post('/api/Image', formData, config)
并且问题解决了!
推荐阅读
- laravel - Laravel Nova 在 newModel() 中创建一个带有动作的模型
- r - 用R中数据框中的最新数据填充缺失的日期
- c# - 命令:dotnet ef migrations add "Initial Application Migrations" 弹出这个奇怪的错误
- asp.net - 401 - 未经授权:由于凭据无效,访问被拒绝。您无权使用凭据查看此目录或页面
- r - pivot_wider() 为以前的完整数据生成 NA
- c# - 如何将公共包从 github 添加到我的 .Net 解决方案
- java - 如何在Java中向线程发送信号
- jenkins - linux中同一个tomcat服务器上的多个Jenkins
- windows - 窗口(win32 UI)刷新不正确
- node.js - Express Node js、React js 和 Passport js (OAuth2) 通信问题(API 响应)