我正在尝试将表单数据中的图像发送到API node.js服务器,但每次都会给我错误 console.log(fd.getAll('image')[0])
它带有正确的文件,
这是我的HTML代码
<form @submit.prevent>
<input type="text" placeholder="اسم القسم" v-model="name">
<input type="file" @change="fileSelected">
<button @click="addCategory" class="button--edit">اضف قسم جديد</button>
</form>
javascript代码:
fileSelected(event){
this.selectedFile = event.target.files[0]
},
addCategory(){
const token = this.$store.state.idToken.token;
const file = this.selectedFile;
const fd = new FormData();
const name = this.name
fd.append('image', file);
//console.log(fd.getAll('image')[0])
axios({
method: 'post',
url: '/admin/support/catigory',
data: {
image: fd,
name: name
},
headers: {
'Authorization': `Basic ${token}`,
}
})
.then(res => {
console.log(res)
})
.catch(err => {
console.log(err.response)
})
}
这是后端功能:
exports.postRoute = async (req, res, next) => {
const name = req.body.name;
const image = req.files;
const errors = validationResult(req);
try {
if (!errors.isEmpty()) {
const error = new Error(
`validation faild for ${errors.array()[0].param} in the ${
errors.array()[0].location
}`
);
error.statusCode = 422;
throw error;
}
if (image.length == 0) {
const error = new Error("validation faild.. you should insert image");
error.statusCode = 422;
throw error;
}
这是错误: error in console
我也尝试添加:
'Content-Type': `multipart/form-data` to the herders but nothing changed