【问题标题】:Unhandled promise rejection: SyntaxError: JSON Parse error: Unrecognized token '<' in react native未处理的承诺拒绝:SyntaxError: JSON Parse error: Unrecognized token '<' in react native
【发布时间】:2021-06-07 00:54:42
【问题描述】:

我是原生反应的新手。我创建了一个表单来将图像上传到服务器。但是当我尝试上传图片时不断收到这样的错误=> [未处理的承诺拒绝:SyntaxError:JSON 解析错误:无法识别的令牌'

这是我的代码

 const pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
     // base64: true,
    });
    if (result.cancelled) {
      return;
    }
  
    let localUri = result.uri;
    let filename = localUri.split('/').pop();
  
    let match = /\.(\w+)$/.exec(filename);
    let type = match ? `image/${match[1]}` : `image`;
  
    let formData = new FormData();
    formData.append('photo', { uri: localUri, name: filename, type });
  
    console.log(formData)
    return await fetch('https//xyxtech/Android_API_CI/upload_multipart_data', {
      method: 'POST',
      body: formData,
      // header: {
      //   'content-type': 'multipart/form-data',
      // },
      headers: {'Accept': 'application/json, text/plain, */*', 'content-type': 'multipart/form-data'},
    })
    .then((returnValue) => returnValue.json())
  // .catch(err=>err)
  .then(function(response) {
    console.log(response)
    Alert.alert("File uploaded");
    // return response.json();
  });
  };

【问题讨论】:

  • 将您的图像上传到aws 并将相同的link 提供给服务器端。这是一个很好的做法。

标签: react-native multipartform-data multipart


【解决方案1】:

这本身不是 React Native 问题。您的服务器使用无法在此处解析的非 JSON 正文进行响应:

.then((returnValue) =&gt; returnValue.json())

这可能意味着您的 HTTP 请求不正确。为什么它不正确 - 抱歉,无法帮助您,因为我不熟悉您尝试使用的 API。

【讨论】:

  • 好的,当我删除它时,我的警报是打印的,但我没有得到任何回应。它说=向您的开发环境发送日志消息时出现问题
  • 试试console.log(JSON.stringify(response))
  • 将多部分格式的数据发送到服务器是否正确
  • 我怎么知道它完全正常工作,因为有些人说它的代码正确但在我的服务器图像中没有得到
【解决方案2】:

我遇到了类似的错误,就像其他贡献者所说的那样,问题不在于前端(React-Native 代码 sn-p),而在于后端(API)。我接受。该错误还表明 fetch 调用工作正常。因此,您需要测试您的 API 以确认它返回正确的输出。使用邮递员或浏览器。为变量 photo 赋值并调用 https//xyxtech/Android_API_CI/upload_multipart_data。否则一切都会好起来的。

【讨论】:

    猜你喜欢
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 2021-06-25
    • 2016-12-15
    • 2020-07-03
    • 1970-01-01
    • 2017-12-20
    相关资源
    最近更新 更多