Home > Enterprise >  Network Error on formdata POST request React Native
Network Error on formdata POST request React Native

Time:07-08

I always get an Error: Network Error when trying to send a formData post request with axios. I tried to use fetch, xmlhttprequest, upgrade and downgrade axios/react-native... but no success. The thing is that sending the same content body on Insomnia/Postman returns a successful 200. Maybe it is something with the react-native way of creating/formatting a formData.

axios: 0.27.2
react-native: 0.64.2
react: 16.13.1

const sendAnswer = async () => {
  if (!validateForm()) return false;

  setPostLoading(true);

  const body = new FormData();
  const answersData = answers;

  answersData.forEach((answerData) => {
    const newAnswer = answerData;
    const { tipo_dado: type, resposta: answer } = newAnswer;

    if (type === 'imagem' || type === 'assinatura') {
      body.append(newAnswer.sub_id, {
        name: answer.name,
        uri: answer.uri,
        type: answer.type,
      });

      delete newAnswer.resposta;
    }

    return newAnswer;
  });
    
  body.append('formulario_id', formData._id);
  body.append('respostas', answersData);
  body.append('usuario_id', userData.id);

  try {
    const formResponse = await api.post(API_ANSWERS, body, {
      headers: {
        Accept: 'application/json',
        'Content-Type': 'multipart/form-data;',
      },
      transformRequest: (data) => data,
    });
  } catch (error) {
    console.log(error)
  } finally {
    setPostLoading(false);
  }
};

edit: error object

{
    "message": "Network Error",
    "name": "AxiosError",
    "config": {
        "transitional": {
            "silentJSONParsing": true,
            "forcedJSONParsing": true,
            "clarifyTimeoutError": false
        },
        "transformResponse": [
            null
        ],
        "timeout": 5000,
        "xsrfCookieName": "XSRF-TOKEN",
        "xsrfHeaderName": "X-XSRF-TOKEN",
        "maxContentLength": -1,
        "maxBodyLength": -1,
        "env": {
            "FormData": null
        },
        "headers": {
            "Accept": "application/json",
            "Content-Type": "multipart/form-data",
            "Authorization": "secret_token_here"
        },
        "baseURL": "https://server.com.br",
        "method": "post",
        "url": "https://server.com.br/api-mobile/",
        "data": {
            "_parts": [
                [
                    "6256b36ad1d2220009e9d6b1",
                    {
                        "name": "rn_image_picker_lib_temp_6dc1b2ae-f170-4f9a-b763-d4be94ccbcd7.jpg",
                        "uri": "file://data/user/0/br.com.rotaexata.rastreador/cache/rn_image_picker_lib_temp_6dc1b2ae-f170-4f9a-b763-d4be94ccbcd7.jpg",
                        "type": "image/jpeg"
                    }
                ],
                [
                    "6256b36ad1d2220009e9d6b2",
                    {
                        "name": "image-1657132824768.png",
                        "uri": "file://data/user/0/br.com.rotaexata.rastreador/cache/image-1657132824768.png",
                        "type": "image/png"
                    }
                ],
                [
                    "formulario_id",
                    "6256b36ad1d2220009e9d6b3"
                ],
                [
                    "respostas",
                    [
                        {
                            "pergunta": "Qual a data?",
                            "tipo_dado": "data",
                            "options": [],
                            "obrigatorio": 0,
                            "sub_id": "6256b36ad1d2220009e9d6af",
                            "resposta": "2022-07-19"
                        },
                        {
                            "pergunta": "Qual o horário?",
                            "tipo_dado": "hora",
                            "options": [],
                            "obrigatorio": 0,
                            "sub_id": "6256b36ad1d2220009e9d6b0",
                            "resposta": "19:34"
                        },
                        {
                            "pergunta": "Insira uma imagem ",
                            "tipo_dado": "imagem",
                            "options": [],
                            "obrigatorio": 1,
                            "sub_id": "6256b36ad1d2220009e9d6b1"
                        },
                        {
                            "pergunta": "Assine por favor",
                            "tipo_dado": "assinatura",
                            "options": [],
                            "obrigatorio": 1,
                            "sub_id": "6256b36ad1d2220009e9d6b2"
                        }
                    ]
                ],
                [
                    "usuario_id",
                    26523
                ]
            ]
        }
    },
    "code": "ERR_NETWORK",
    "status": null
}

edit2: error response

{
    "UNSENT": 0,
    "OPENED": 1,
    "HEADERS_RECEIVED": 2,
    "LOADING": 3,
    "DONE": 4,
    "readyState": 4,
    "status": 0,
    "timeout": 5000,
    "withCredentials": true,
    "upload": {},
    "_aborted": false,
    "_hasError": true,
    "_method": "POST",
    "_perfKey": "network_XMLHttpRequest_1011",
    "_response": "Unrecognized FormData part.",
    "_url": "https://server.com.br/api-mobile/",
    "_timedOut": false,
    "_trackingName": 1011,
    "_incrementalEvents": true,
    "_performanceLogger": {
        "_timespans": {
            "network_XMLHttpRequest_1001": {
                "startTime": 1493.8999999985099,
                "endTime": 1701.8999999985099,
                "totalTime": 208
            },
            "network_XMLHttpRequest_1002": {
                "startTime": 1793,
                "endTime": 3764.7999999970198,
                "totalTime": 1971.7999999970198
            },
            "network_XMLHttpRequest_1003": {
                "startTime": 1793.699999999255,
                "endTime": 2188.5,
                "totalTime": 394.80000000074506
            },
            "network_XMLHttpRequest_1004": {
                "startTime": 1794.199999999255,
                "endTime": 2632.7999999970198,
                "totalTime": 838.5999999977648
            },
            "network_XMLHttpRequest_1005": {
                "startTime": 1928.5,
                "endTime": 2613.89999999851,
                "totalTime": 685.3999999985099
            },
            "network_XMLHttpRequest_1006": {
                "startTime": 2057.7999999970198,
                "endTime": 2880.39999999851,
                "totalTime": 822.6000000014901
            },
            "network_XMLHttpRequest_1007": {
                "startTime": 4016.699999999255,
                "endTime": 4833.199999999255,
                "totalTime": 816.5
            },
            "network_XMLHttpRequest_1008": {
                "startTime": 4017.099999997765,
                "endTime": 4855.599999997765,
                "totalTime": 838.5
            },
            "network_XMLHttpRequest_1009": {
                "startTime": 4017.5,
                "endTime": 4882.89999999851,
                "totalTime": 865.3999999985099
            },
            "network_XMLHttpRequest_1010": {
                "startTime": 9463.79999999702,
                "endTime": 9774.199999999255,
                "totalTime": 310.4000000022352
            },
            "network_XMLHttpRequest_1011": {
                "startTime": 49170.599999997765
            }
        },
        "_extras": {},
        "_points": {
            "initializeCore_start": 914.2999999970198,
            "initializeCore_end": 935.2999999970198
        },
        "_pointExtras": {},
        "_closed": false
    },
    "_requestId": null,
    "_headers": {
        "accept": "application/json",
        "content-type": "multipart/form-data",
        "authorization": "secret_token_here"
    },
    "_responseType": "",
    "_sent": true,
    "_lowerCaseResponseHeaders": {},
    "_subscriptions": []
}

CodePudding user response:

I solved it. This comment helped me.

When you want to append objects to the formData you need to convert them to JSON, so I converted the main array of objects with JSON.stringify(answersData)

body.append('formulario_id', formData._id);
body.append('respostas', JSON.stringify(answersData));
body.append('usuario_id', userData.id);

CodePudding user response:

In react-native way of creating/formatting a formData works like everywhere. Anyway let's try to check this:

  • If you make query to a remote server, make sure you use https format.

  • If you make query to a local server on android simulator try use "http:// 10.0.2.2:8000/" instead "http:// localhost:8000/" format.

  • And seems you did mistake in the row: 'Content-Type': 'multipart/form-data;', Try to remove semicolon.

If that won't help you, send me the full error object.

  • Related