formdata POST请求React Native时出现网络错误

hivapdat  于 2022-11-25  发布在  React
关注(0)|答案(2)|浏览(210)

当我尝试用axios发送formData post请求时,总是得到Error: Network Error。我尝试使用fetch、xmlhttprequest、升级和降级axios/react-native. a.. a.但是没有成功。问题是,在Insomnia/Postman上发送相同的内容正文会成功返回200。可能是react-native创建/格式化formData的方式有问题。
坐标轴: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);
  }
};
  • 编辑:错误对象 *
{
    "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
}

edit 2:错误响应

{
    "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": []
}
6yjfywim

6yjfywim1#

我解决了这个问题。这条评论帮助了我。
当您想要将对象追加到formData时,需要将它们转换为JSON,因此我使用JSON.stringify(answersData)转换了对象的主数组

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

hujrc8aj2#

在react-native方式创建/格式化一个formData像任何地方一样工作。无论如何让我们试着检查一下:

  • 如果要查询远程服务器,请确保使用https
  • 如果您在Android模拟器上查询本地服务器,请尝试使用“http:10.0.2.2:8000/“而不是“http://localhost:8000/”格式。
  • 而且似乎是你在争吵中犯了错误:'Content-Type': 'multipart/form-data;',尝试删除分号。

如果这对您没有帮助,请将完整的错误对象发送给我。

相关问题