node.jsreact-nativemultipartform-datamulterreact-native-image-picker

React native sends empty req.body and undefined req.file to nodejs multer


Im using react-native and nodejs(multer). In nodejs I receive req.body-{}, req.file-undefined and req.files-undefined

I checked everything in stackoverflow and nothing works. Here is my code.

Client code(react native):

const onPressOpenLibrary = async () => {
        const result = await launchImageLibrary({
            maxHeight: 200,
            maxWidth: 200,
            selectionLimit: 0,
            mediaType: 'photo',
            includeBase64: true
        })

        if (result.assets) {
            const formData = new FormData()

            formData.append('name', 'Alexander')
         
            formData.append('avatar', {
                uri: result.assets[0].uri,
                type: result.assets[0].type,
                name: result.assets[0].fileName
            })

            setResult(result)

            axios.post('upload-image', formData, {
                headers: {
                    'Content-Type': `multipart/form-data;`
                }
            })
        }
    }

Server code(nodejs):

app.use(express.urlencoded({ extended: false }))
app.use(express.json())
...
const upload = multer({
    dest: 'uploads/'
})

router.post(
    '/upload-image',
    upload.single('avatar'),
    async (req: Request, res: AppResponse, next: NextFunction) => {
        console.log('upload image body', req.body) // -> {}
        console.log('upload image files', req.files) // -> undefined
        console.log('upload image file', req.file) // -> undefined
    }
)

What I tried:

What could be the problem and eventually the solution?


Solution

  • Problem: Cant send text or image FormData from react native with axios or fetch.

    Solution: Downgraded axios to axios: ^0.24.0.