Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);
        });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
220 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...