React Native unable to send form data to backend

Viewed 286

I'm just trying to do a simple form where the user can make a post in react native for ANDROID. The form should send the text data and image to the backend server but only the text data is being sent. Currently using these 2 modules to get the image, which is then converted to base64

import { Picker } from '@react-native-picker/picker';
import ImagePicker from 'react-native-image-crop-picker';

const [images, setImages] = useState([]);

const takePhotoFromCamera = () => {
    ImagePicker.openCamera({
      compressImageMaxWidth: 300,
      compressImageMaxHeight: 300,
      cropping: true,
      compressImageQuality: 0.8,
      includeBase64: true,
    }).then(image => {
      setImages(images => [...images, {
        uri: image.data,
        name: "image_name",
        type: image.mime,
      }]);
    }).catch(error => console.log(error));
  }

const choosePhotoFromLibrary = () => {
    ImagePicker.openPicker({
      width: 300,
      height: 300,
      cropping: true,
      compressImageQuality: 0.8,
      includeBase64: true,
    }).then(image => {
      setImages(images => [...images, {
        uri: image.data,
        name: "image_name",
        type: image.mime,
      }]);
    }).catch(error => console.log(error));
  }

Data is added to a formdata and sent to backend server, URL of the server has already been replaced with my laptop IP, I am supposed to be able to upload multiple images, but was only trying with 1 image for testing

async function sendImageToServer() {
    setLoading(true);
    try {
        const formData = new FormData();
        formData.append("file", { name: images[0].name, type: images[0].type, uri: images[0].uri })   
        formData.append(
            "questionData", 
            JSON.stringify({
                questionTitle: questionTitle,
                questionContent: postText,
                questionObjective: selectedObj
            })
        );
        axios.post(
            `http://${myIP}:5000/question/create`,
            formData, {
                headers: {
                    "authorization": "Bearer jljlkjl",
                    "Content-Type": "multipart/form-data; boundary=someRandomString",
                    "Accept": "application/json"
                }
            }).then(results => {
                console.log(results)
            }).catch(error => {
                console.log(error)
            })        
    } catch(error) {
        console.log(error);
    } finally {
        setLoading(false);
    }
} 

For some reason React native won't let me send the post request if ALL the data in the formData is stringified, which includes the file as well. Whenever I try to send a request like this I keep receiving [Error: Network Error] in the console, the only way for the request to be sent is when I send the file data like this:

formData.append("file", JSON.stringify({ name: images[0].name, type: images[0].type, uri: images[0].uri })); 

but when I do this my backend becomes unable to detect it as a file.

Currently using Multer for parsing multipart/form-data

//import mutler 
const multer = require("multer");
const upload = multer({ 
    storage: multer.memoryStorage(), 
    limits: { fileSize: 2000000, files: 2 }, //set limit for file size and number of file fields 
    fileFilter: (req, file, cb) => { //limit the file extentions
        let ext = path.extname(file.originalname);
        if (ext !== ".jpg" && ext !== ".png" && ext !== ".jpeg") {
            cb(new FileError("File Type Not Supported!"), false);
            return;
        }
        cb(null, true);
    }
});
router.post("/question/create", verifyFn.verifyToken, upload.array("file", 5), validationFn.validateCreateForumQuestion, questionController.createForumQuestion);

This seems to be working when I did testing with postman to send files in the req body form-data but multer doesn't seem to be able to detect the file when I send it from my React native app as a stringified JSON.

The file appears in the request body but the req.files will always be an empty array.

Body:
[Object: null prototype] {
  file: '{"name":"image_name","type":"image/jpeg","uri":"/9j/4AAQSkZJRgABAQAAAQAB....

Is there any way I can force React native to allow me to send non-stringified data or any way for me to parse the form data into json before multer middleware so that multer can detect it? Any help would be appreciated.

All my current modules:

"dependencies": {
    "@react-native-picker/picker": "^2.1.0",
    "@react-navigation/native": "^6.0.6",
    "@react-navigation/native-stack": "^6.2.5",
    "axios": "^0.24.0",
    "i": "^0.3.7",
    "npm": "^8.1.3",
    "react": "17.0.2",
    "react-native": "0.66.1",
    "react-native-elements": "^3.4.2",
    "react-native-gesture-handler": "^1.10.3",
    "react-native-htmlview": "^0.16.0",
    "react-native-image-crop-picker": "^0.36.4",
    "react-native-pell-rich-editor": "^1.8.6",
    "react-native-safe-area-context": "^3.3.2",
    "react-native-screens": "^3.9.0",
    "react-native-svg": "^12.1.1",
    "react-native-vector-icons": "^9.0.0",
    "react-native-webview": "^11.14.2",
    "reanimated-bottom-sheet": "^1.0.0-alpha.22"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "@babel/runtime": "^7.12.5",
    "@react-native-community/eslint-config": "^2.0.0",
    "babel-jest": "^26.6.3",
    "eslint": "7.14.0",
    "jest": "^26.6.3",
    "metro-react-native-babel-preset": "^0.66.2",
    "react-test-renderer": "17.0.2"
  }
0 Answers
Related