我无法通过浏览器从我的vuejs前端发送上传的文件到nodejs后端,但是在与邮递员发送时,它可以正常工作。 我在nodejs中收到此警告:“((node:3708)UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性'buffer'”,但不会使应用程序崩溃。 这是我的代码:
//.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})
})
请谁能告诉我我在做什么不对?谢谢。