I am new to React Native and trying to upload Image with Axios but getting: Request failed with status code 500
I don't have backend problem because I can upload image with postman and everything is fine.
Here is my code, please help me if you know a solution, when I console log data, all the data are fine!!
const data = new FormData();
data.append('name', name);
data.append('childrenImage', childrenImage);
data.append('parent', parent)
console.log(data);
axios.post('http://192.168.0.24:3000/childrens/', data, {
headers: {
'Authorization': auth,
'accept': 'application/json',
'Content-Type': `multipart/form-data`
}
}
).then(res => {
console.log(res.data);
console.log(res.status);
})
.catch(err => {
console.log(err.message);
});
Can't be sure but in my case I had to add a 'name' field to the file. Following other advices, I've end up with something like this:
import axios from 'axios';
import FormData from 'form-data';
function upload (data, images, token) {
const formData = new FormData();
formData.append('data', data);
images.forEach((image, i) => {
formData.append('images', {
...image,
uri: Platform.OS === 'android' ? image.uri : image.uri.replace('file://', ''),
name: `image-${i}`,
type: 'image/jpeg', // it may be necessary in Android.
});
});
const client = axios.create({
baseURL: 'http://localhost:3001',
});
const headers = {
Authorization: `Bearer ${token}`,
'Content-Type': 'multipart/form-data'
}
client.post('/items/save', formData, headers);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With