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
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:This solves the error for me.
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:
Check network connectivity:
Handle network errors:
error.request
object in thecatch
block. For example:Allow insecure connections (if applicable):
axios.defaults.validateStatus
option to a function that always returnstrue
:Verify the API endpoint and request format:
apiURL
) in your React Native code is correct and matches the endpoint you are trying to reach.multipart/form-data
).Test the API endpoint separately:
Enable CORS (Cross-Origin Resource Sharing):
By following these steps, you should be able to identify and resolve the network error you’re encountering in your React Native code.