req.file undefined при загрузке изображения через axios в multer на сервер node.js

Frontend (Expo)

'''
const [image, setImage] = useState(null)

    const pickImage = async () => {
      const result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.Images,
        allowsEditing: true,
        aspect: [1, 1],
        quality: 1,
      });

      if (result) {
        setImage(result.uri);
          
    }}

const uploadFile = React.useCallback( async () => {
    const formData = new FormData();
        formData.append('avatar', image)

          try {const res = await client.post('/upload-avatar', formData, {
              headers: {
                Accept: 'application/json',
                'Content-Type': 'multipart/form-data; boundary=XXX',
                authorization: 'JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2MjRmZGZhOTA3OWM2NGQxMDQ5NmJlYjAiLCJpYXQiOjE2NDk3ODA2MzEsImV4cCI6MTY0OTg2NzAzMX0.COL_LkgveXjI31_aHhqB6Z_wiXxtRn2IQ50oQE9gmzw'
              }
            })
            console.log(res.data)
            console.log(formData)
          } catch (error) {
            console.log(error.message)
            console.log(formData)
          }}, [image])
'''

Backend (Node.Js)

'''
const storage = multer.diskStorage({})

const fileFilter = (req, file, cb) => {
    if(file.mimetype.startsWith('image')){
        cb(null, true)
    }else{
        cb('invlid image file', false)
    }
}
const uploads = multer({storage, fileFilter})

router.post('/upload-avatar', isAuth, uploads.single('avatar'), async (req, res) => {
    const {user} = req
    if(!user) return res.status(401).json({success: false, message: 'unauthorized access!'})
    

    console.log(req.file) //req.file here always undefined
    try {
        const profileBuffer = req.file.path
        
    const {width, height} = await sharp(profileBuffer).metadata()
    const avatar = await sharp(profileBuffer).resize(Math.round(10), Math.round(10)).toBuffer()
    await User.findByIdAndUpdate(user._id, {avatar})
    res.status(201).json({success: true, message: 'Фото загружено'})
    } catch (error) {
        res.status(500).json({success: false, message: 'Error with avatar image'})
        console.log(error.message)
        
    }
})
'''

Console Frontend:

'''
Request failed with status code 500
FormData {
  "_parts": Array [
    Array [
      "avatar",
      "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252FPartyFind-5ce93ea7-3c91-4a06-b988-2f80c5b80c80/ImagePicker/9edd8f26-2fa0-47a1-a2c5-7381438d369a.jpg",
    ],
  ],
}
'''

Console Backend:

'''
listening port ${PORT}
our db is connected
undefined
Cannot read properties of undefined (reading 'path')
'''

Backend works with Postman, image uploads to MongoDB, but not with Expo and axios I try everything, but nothing work(


Ответы (0 шт):