【问题标题】:React Native - fetch API error: [SyntaxError: JSON Parse error: Unexpected identifier "object"]React Native - 获取 API 错误:[SyntaxError: JSON Parse error: Unexpected identifier "object"]
【发布时间】:2019-11-27 20:21:30
【问题描述】:

React Native 的新手。我正在尝试使用 FormData 使用来自Spencer Carli 的以下示例使用 fetch API 上传图像和数据。我的后端工作正常,当我使用邮递员时,图像上传到数据库存储没有任何问题。但是当我尝试通过移动设备上传图片时,我得到了

upload error [SyntaxError: JSON Parse error: Unexpected identifier "Tunnel"]

下面是我的代码

     const createFormData = (photo, body) => {
        const data = new FormData();

        data.append('file', {
            name: photo.fileName,
            type: photo.type,
            uri:
                Platform.OS === 'android' ? photo.uri : photo.uri.replace('file://', ''),
            });

        Object.keys(body).forEach(key => {
          data.append(key, body[key]);
        });

        return data;
      };

    const uploadPhotoHandler = async (photo) => {
        const token = await AsyncStorage.getItem('token');
        fetch('http://ba9737b7.ngrok.io/post', {
            headers: {'Authorization': 'Bearer ' + token},
            method: 'POST',
            body: createFormData(photo, {
                title: 'Golden twisted knots',
                postType: 'hair',
                duration: 45}),
          })
          .then(response => response.json())
          .then(response => {
            console.log('upload succes', response);
            alert('Upload success!');
          })
          .catch(error => {
            console.log('upload error', error);
            alert('Upload failed!');
          });
    };

我认为问题出在这一行

    .then(response => response.json())

但我不知道为什么。

【问题讨论】:

  • 您在回复中得到了什么? `Object.keys(body).forEach(key => { data.append(key, body[key]); });` 的目的是什么,你只需要发送文件对象

标签: react-native upload fetch multipartform-data form-data


【解决方案1】:

问题是因为您没有收到 JSON 响应。当您尝试解析为 JSON 时。 你可以先检查响应状态码来解决它,试试这个。

const uploadPhotoHandler = async (photo) => {
        const token = await AsyncStorage.getItem('token');
        fetch('http://ba9737b7.ngrok.io/post', {
            headers: {'Authorization': 'Bearer ' + token},
            method: 'POST',
            body: createFormData(photo, {
                title: 'Golden twisted knots',
                postType: 'hair',
                duration: 45}),
          })
          .then(response => {

            //If the response status code is between 200-299, if so
            if(response.ok) return response.json();

             //if not, throw a error
             throw new Error('Network response was not ok');
          })
          .then(response => {
            console.log('upload succes', response);
            alert('Upload success!');
          })
          .catch(error => {
            console.log('upload error', error);
            alert('Upload failed!');
          });
    };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    • 2021-05-29
    相关资源
    最近更新 更多