【问题标题】:React Native Fetch/ Axios file upload errorReact Native Fetch / Axios文件上传错误
【发布时间】:2021-05-20 08:35:30
【问题描述】:

我在尝试将图像从 React-Native android 模拟器上传到服务器时遇到问题,如果您遇到此问题并已解决,请指出答案或写下答案。

const data = new FormData();
  data.append('file', {
    uri: file.src.uri,
    name: file.src.name,
    type: file.src.type,
  });
  data.append('documentType', file.id);
   // axios({
  //   method: 'post',
  //   url: API_URL + '/users/' + user.id + '/uploadDocument',
  //   body: data,
  //   headers: {
  //     'Content-Type': 'multipart/form-data; ',
  //   },
  // })
  fetch(API_URL + '/users/' + user.id + '/uploadDocument', {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'multipart/form-data',
    },
    body: data,
  })
    .then(async (res) => {
      console.log(res);
      if (res.status === 200) {
        Toast.show({
          text: 'Profile Document Uploaded Successfully',
          position: 'top',
        });
      } else {
        Toast.show({
          text: 'There was an error uploading',
          position: 'top',
        });
      }
    })
    .catch((err) => {
      console.log('Profile img upload err', err.message);
      Toast.show({
        text: 'Unable to upload profile document',
        position: 'top',
      });
    });

这是 Fetch 的响应-

{"_bodyBlob": {"_data": {"__collector": [对象], "blobId": "85366f42-0bb9-48e0-81f6-fb516a41efb3", "offset": 0, "size": 244} },“_bodyInit”:{“_data”:{“__collector”:[对象],“blobId”:“85366f42-0bb9-48e0-81f6-fb516a41efb3”,“offset”:0,“size”:244}}, "bodyUsed": false, "headers": {"map": {"access-control-allow-headers": "x-requested-with, authorization,Content-Type", "access-control-allow-methods": “POST、GET、OPTIONS、DELETE、PUT”、“access-control-allow-origin”:“*”、“access-control-max-age”:“3600”、“cache-control”:“无缓存” , no-store, max-age=0, must-revalidate", "content-type": "application/json;charset=UTF-8", "date": "2021 年 2 月 17 日星期三 12:34:59 GMT ", "expires": "0", "pragma": "no-cache", "server": "nginx/1.12.1", "x-content-type-options": "nosniff", "x-frame -options": "DENY", "x-xss-protection": "1; mode=block"}}, "ok": false, "status": 400, "statusText": undefined, "type": "default ", "url": "https://xxxxxx.yyyyyy.in/users/422/uploadDocument"}

Axios 失败并显示 400 或 500 错误代码

【问题讨论】:

    标签: react-native file-upload axios fetch multipartform-data


    【解决方案1】:

    我相信如果没有来自服务器的更多信息,很难判断错误是什么。 400 Bad Request 错误表示您发送的有效负载存在问题。可能是文件 mime 类型或内容本身。

    500 Internal Error 响应可能表明您发送的内容导致服务器端异常(主要是因为服务器编码不当,无法处理不正确的负载)。

    【讨论】:

    • 谢谢,后端的错误提示信息也不清楚,所以我尝试了Fetch。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    • 2018-11-24
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    • 2020-02-11
    相关资源
    最近更新 更多