skip to Main Content

I want to send a post request to my api by sending an image in react-native but somehow, I’m getting network error. I wrote the same code in python for checking if my flask api is working properly or not and to my suprise it’s working properly by using python code.

I’ll provide both of the code, the code I’ve written in python and the code I’ve written in react-native for doing the same task. I’m using axios for requesting purposes.

React Native code:

 import React, { useState } from 'react';
 import { View, Text, Button, Alert, ActivityIndicator } from 'react-native';
 import { launchImageLibrary } from 'react-native-image-picker';
 import axios from 'axios';

  export default function ImageView() {
    const [result, setResult] = useState('');
    const [isLoading, setIsLoading] = useState(false);

    const handleImageUpload = () => {
      const options = {
        mediaType: 'photo',
        quality: 1,
        includeBase64: false,
      };

      launchImageLibrary(options, (response) => {
        if (response.didCancel) {
          console.log('Image upload canceled');
        } else if (response.error) {
          Alert.alert('Error', response.error);
        } else {
          const formData = new FormData();
          formData.append('file', {
          uri: response.uri,
          type: response.type,
          name: response.fileName || 'image.jpg',
        });

        uploadImage(formData);
        }
       });
      };

    const uploadImage = (formData) => {
    setIsLoading(true);

    const apiURL = 'https://rrd.pythonanywhere.com';

    const fileData = new FormData();
    fileData.append('file', {
      uri: formData.uri,
      type: 'image/jpeg',
      name: 'image.jpg',
    });

    axios
      .post(apiURL, fileData)
      .then((response) => {
        const data = response.data;
        setResult(`${data.plant} - ${data.condition}`);
      })
      .catch((error) => {
        Alert.alert('Error', error.message);
        console.log(error)
      })
      .finally(() => {
        setIsLoading(false);
      });
      };

      return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text style={{ fontSize: 24, color: 'black' }}>Image Upload</Text>
      <Button title="Capture or Upload Image" onPress={handleImageUpload} />
      {isLoading ? (
        <ActivityIndicator size="large" color="black" style={{ marginTop: 20 }} />
      ) : result !== '' ? (
        <View style={{ marginTop: 20 }}>
          <Text style={{ fontSize: 18, color: 'black' }}>Result:</Text>
          <Text style={{ fontSize: 16, color: 'black' }}>{result}</Text>
        </View>
      ) : null}
      </View>
     );
    }

Python code:

import requests

api_url = 'https://rrd.pythonanywhere.com'
image_path = './test_images/0005_0008.jpg'
files = {'file': open(image_path, 'rb')}
response = requests.post(api_url, files=files)

if response.status_code == 200:
    
    data = response.json()
    print(f"Plant: {data['plant']}")
    print(f"Condition: {data['condition']}")
else:
    
    print(f"Request failed with status code {response.status_code}")

I’ll be glad if anyone let me solve this error.

I tried simple react request then switch to axios HTTP request but nothing seems to be working.

2

Answers


  1. Chosen as BEST ANSWER

    I've spend a lot researching the error and I found out that the launchImageLibrary(options, (response) , repsonse have an array of data when I upload an image from the gallery. Before realising that when I console log, uri, type and name, the answer I got is undefined. so what I did is in the following way:

     const handleImagePickerResponse = (response) => {
        console.log('Image Picker Response:', response);
      
        if (response.didCancel) {
          console.log('Image upload canceled');
        } else if (response.error) {
          Alert.alert('Error', response.error);
        } else {
          const { uri, type, fileName } = response.assets[0];
          console.log("uri: ", uri);
          console.log("type", type);
          console.log("name:", fileName);
      
          if (uri) {
            const formData = new FormData();
            formData.append('file', {
              uri,
              type,
              name: fileName || 'image.jpg',
            });
      
            setSelectedImageSource(uri);
            uploadImage(formData);
          }
        }
      };
      

    This solves the error for me.


  2. The network error you’re experiencing in your React Native code could be caused by various factors. Here are a few suggestions to help you troubleshoot and fix the issue:

    1. Check network connectivity:

      • Ensure that your mobile device has a stable internet connection. Try accessing other websites or making API requests from other apps to confirm connectivity.
    2. Handle network errors:

      • Modify your React Native code to handle network errors specifically, in addition to catching general errors. You can check for network-related errors using the error.request object in the catch block. For example:
        .catch((error) => {
          if (error.request) {
            // Network error
            console.log('Network error', error.request);
          } else {
            // Other error
            console.log('Error', error.message);
          }
        })
        
    3. Allow insecure connections (if applicable):

      • If your API is served over an insecure HTTP connection (not HTTPS), you might need to configure your network settings or use a network library that allows insecure connections. Note that this should only be used for testing and not in a production environment.
      • To allow insecure connections with Axios, you can set the axios.defaults.validateStatus option to a function that always returns true:
        axios.defaults.validateStatus = () => true;
        
    4. Verify the API endpoint and request format:

      • Double-check that the API URL (apiURL) in your React Native code is correct and matches the endpoint you are trying to reach.
      • Confirm the request format required by your API. Ensure that you are sending the image data in the correct format (multipart/form-data).
      • Compare the request structure between your Python code and React Native code to make sure they align. Pay attention to headers, data fields, and file formatting.
    5. Test the API endpoint separately:

      • Use tools like Postman or cURL to directly send requests to your API endpoint from your development machine or server. This will help you isolate the issue to the React Native code or the API itself.
    6. Enable CORS (Cross-Origin Resource Sharing):

      • If your API and React Native app are hosted on different domains, ensure that your API server is configured to allow cross-origin requests from your app’s domain. You can add appropriate CORS headers to your server’s responses to enable this.

    By following these steps, you should be able to identify and resolve the network error you’re encountering in your React Native code.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search