I’m trying to connect my React Native app to an image processing API through RapidAPI but running into some problems. The API changed from accepting base64 strings to requiring file uploads, and I can’t figure out how to make it work properly.
I’m using react-native-image-picker to select photos from the device gallery. Here’s what the API documentation shows:
import fetch from "node-fetch";
const formData = new FormData();
formData.append("photo", "");
formData.append("quality", "30");
const config = {
method: 'POST',
url: 'https://image-enhancer.p.rapidapi.com/process-image-endpoint',
headers: {
'content-type': 'multipart/form-data',
'x-rapidapi-host': 'image-enhancer.p.rapidapi.com',
'x-rapidapi-key': 'YOUR_API_KEY'
},
body: formData
};
fetch(config).then(res => res.json()).then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
My current implementation looks like this:
import React, {useState} from 'react';
import {View, Alert, StyleSheet} from 'react-native';
import {TouchableOpacity} from 'react-native-gesture-handler';
import LoadingSpinner from 'react-native-loading-spinner-overlay';
import {launchImageLibrary} from 'react-native-image-picker';
import axios from 'axios';
const ImageProcessor = () => {
const [isVisible, setIsVisible] = useState(true);
const [resultData, setResultData] = useState(null);
const [isProcessing, setIsProcessing] = useState(false);
const [imageData, setImageData] = useState(null);
const [imageName, setImageName] = useState(null);
const pickImageFromGallery = () => {
const pickerOptions = {
includeBase64: true,
mediaType: 'photo'
};
launchImageLibrary(pickerOptions, result => {
if (result.didCancel) {
console.log('User cancelled picker');
} else if (result.errorMessage) {
console.log('Picker error occurred');
} else {
setImageData(result.assets[0].base64);
setImageName(result.assets[0].fileName);
processSelectedImage();
}
});
};
const processSelectedImage = () => {
const requestForm = new FormData();
requestForm.append('photo', imageName);
requestForm.append('quality', '15');
setIsVisible(false);
console.log('Processing image');
axios({
method: 'POST',
url: 'https://image-enhancer.p.rapidapi.com/process-image-endpoint',
headers: {
'content-type': 'multipart/form-data',
'x-rapidapi-host': 'image-enhancer.p.rapidapi.com',
'x-rapidapi-key': 'MY_SECRET_KEY',
},
data: requestForm,
})
.then(res => {
setIsProcessing(false);
setResultData(res.data);
})
.catch(err => {
console.error(err);
});
};
return (
// component JSX here
);
};
export default ImageProcessor;
I keep getting a 500 error and I’m not sure what I’m doing wrong. The test endpoint works fine but doesn’t show example responses. Any ideas on how to properly send the image file?