'React native image upload TypeError: Network request failed
I am trying to upload image to my api. Uploading with postman works fine. When I previously used expo go all worked fine as well. Once I switched to react native native code I get following error. I am sure my endpoint is correct and it is HTTPS. Other post request that are not multipart/form data/PUT requests or Get requests work perfectly. Here is code:
const openImagePickerAsync = async () => {
let permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (permissionResult.granted === false) {
alert("Permission to access camera roll is required!");
return;
}
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
quality: 1,
});
console.log(result)
const { cancelled } = result as ImageInfo
if(cancelled == false)
{
const { uri } = result as ImageInfo
const bodyy = new FormData();
const bod = JSON.parse(JSON.stringify({ uri: uri, type: 'image/jpeg', name: 'profilePicture'+userId+".jpg" }));
bodyy.append('demo_image', bod);
try{
const log = await fetch("https://endpoint/api/upload/picture/" + userId, {
method:'POST',
body: bodyy,
headers: {
'Content-Type': 'multipart/form-data',
Accept: "application/json",
}
})
console.log(log)
Alert.alert("Profile picture uploaded!")
}
catch (error){
console.log(error)
}
}
else{
Alert.alert("You did not choose picture to upload.")
}
}
Edit1: I have also tried running my server on localhost with http and writing IPv4 address of my PC I am running server on (besides localhost:8000) I wrote ip:8000. Did not help..
Solution 1:[1]
your problem is about CORS (Cross-Origin Resource Sharing)
you must be add this command in your server
npm install express cors
const express = require('express')
const cors = require('cors')
const app = express()
app.use(cors())
and cors() allowed the client to access this route
but if you didnt use express you can solve this problem with cors header request
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'multipart/form-data',
}```
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Moein T |

