无法读取未定义的属性“缓冲区”

时间:2019-10-04 13:14:41

标签: reactjs mongodb express multer

我想在服务器端使用expressjs和multer将图像存储在mongodb中作为缓冲区类型,而在客户端使用Reactjs将图像存储在mongodb中,我已经在邮递员中尝试过了,它虽然可以正常工作,但是通过react不能正常工作

uploading image using postman successfuly

表达代码

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)
    }
})

router.post('/users/me/avatar', auth, upload.single('avatar'), async (req, res) => {
    console.log(req.file)

     const buffer = await sharp(req.file.buffer).resize({ width: 250, height: 250 }).png().toBuffer();

    console.log(buffer)
    req.user.avatar = buffer
    await req.user.save()

    res.send('image uploaded successfully')
}, (error, req, res, next) => {
    res.status(400).send({ error: error.message })
})

我的React请求

   const onChangeHandler =(e)=>{
      e.persist();
      const file = e.target.files[0];
      setModifier(modifier=>({...modifier,image:file}));
    }

   const addAvatar = async(e)=>{
            e.preventDefault(); 
            const token = localStorage.getItem('jwtToken');
            const res = await axios.post( `http://localhost:5000/users/me/avatar`,modifier.image,{ headers:{"Authorization" :`Bearer ${token}`}})
              try {
                 console.log(res,'sucsses')
              } catch (error) {
                  console.error(error)
              }
    }

0 个答案:

没有答案