使用axios发送文件时反应本机获取网络错误

时间:2020-06-03 12:31:27

标签: react-native file-upload axios api-platform.com

我正在使用api平台创建端点来处理图像上传。 我的api需要文件类型才能发出发布请求。 这是使用post man的帖子请求示例:

enter image description here

我想使用React Native处理与axios发送的图像。

我创建了这样的发帖请求:

 this.setState({
      avatarSource: source,
    });

    console.log(this.state.avatarSource.uri);
    const data = new FormData();

    data.append('file', {
      uri: this.state.avatarSource.uri,
      // show full image path in my device
      //  file:///storage/emulated/0/Pictures/image-c40b64fc-6d74-46a7-9016-191aff3740dd.jpg
    });

    axios
      .post(`${API.URL}/media_objects`, data, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      })
      .then((resp) => console.log(resp))
      .catch((err) => console.log(err.message));
  }
});

我正在将手机中的图像的完整路径发送到api,但出现“网络错误”

1 个答案:

答案 0 :(得分:1)

我通过在ReactNativeFlipper.java中注释此行来解决此问题:

  NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
  NetworkingModule.setCustomClientBuilder(
      new NetworkingModule.CustomClientBuilder() {
        @Override
        public void apply(OkHttpClient.Builder builder) {
          // builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin)); // add comment here and build android 
        }
      });
  client.addPlugin(networkFlipperPlugin);
  client.start();