Я не могу отправить загруженные файлы из моего интерфейса vuejs через браузер на серверную часть nodejs, но он отлично работает при отправке почтальоном.
Я получаю это предупреждение в nodejs: "(node: 3708) UnhandledPromiseRejectionWarning: TypeError: Невозможно прочитать свойство 'buffer' of undefined", но это не приводит к сбою приложения.
Вот мои коды:
//.vue file
<template>
<picture-input
ref="pictureInput"
@change="onChange"
width="250"
height="250"
margin="16"
accept="image/jpeg,image/png"
size="10"
buttonClass="btn"
:customStrings="{
upload: '<h1>Bummer!</h1>',
drag: 'Drag and drop your profile picture or click to upload'
}">
</picture-input>
</template>
method: {
onChange (profilePicture) {
if (profilePicture) {
this.profilePicture = profilePicture
console.log(this.profilePicture)
let formData = new FormData()
formData.append("avatar", this.profilePicture)
const config = {
headers: {
'Content-Type': 'multipart/form-data'
}
}
axios.post("/users/me/avatar", formData, config)
.then(res => {
console.log(res)
})
.catch(error => console.log(error.response))
} else {
throw new Error()
}
}}
//Server.js
const upload = multer({
limits: {
fileSize: 1000000
},
fileFilter(req, file, cb) {
if (!file.originalname.match(/\.(jpg|jpeg|png)$/)) {
return cb(new Error("Please upload an image"))
}
cb(undefined, true)
}
})
userRoutes.post("/users/me/avatar", auth, upload.single("avatar"), async (req, res) => {
const buffer = await sharp(req.file.buffer).resize({width: 250, height: 250}).png().toBuffer()
req.user.avatar = buffer
await req.user.save()
res.send()
}, (error, req, res, next) => {
res.status(400).send({error: error.message})
})
Пожалуйста, кто-нибудь может сказать мне, что я не делаю правильно? Спасибо.