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:
- in react native when I pick and safe in state the response I have
<Image source={{ uri: result.assets[0].uri }} style={{ width: 200, height: 200 }} />
and image is displayed properly. - from postman everything working
- from axios and fetch on the client side not working
What could be the problem and eventually the solution?
CodePudding user response:
result.assets[0].uri
return a reference of a local cached image on device memory but you can not directly upload that image raw data to a remote server.
You should either upload the image as base64
or BLOB
data.
CodePudding user response:
Problem:
Cant send text or image FormData
from react native
with axios or fetch.
Solution:
Downgraded axios to axios: ^0.24.0
.