React Native Fetch give error "Network request failed" - javascript

I have the following code for creating an event with a image and some body params. It was working fine when i was doing it without image, i am using react-native-image-crop-picker for selecting images. I am getting "Network request failed" error when posting data from react-native. The request never reach my backend as i am getting no logs there. It is working fine with postmen.
MY CODE:
const { name, date, description, location, uri, mime, time } = this.state;
const formData = new FormData();
formData.append('name', name)
formData.append('date', date)
formData.append('description', description)
formData.append('location', location)
formData.append('time', time)
formData.append('image',{
uri:uri,
mime:'image/jpeg',
name:`image${moment()}`
})
alert(JSON.stringify(formData));
const config = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formData,
};
fetch(`http://${Config.apihost}:${Config.port}/events`,config).then((res) => res.json())
.then((res) => {
this.setState({ modalVisible: false, name:'', date: moment().format('YYYY-MM-DD'), description:'', Location: 'AlHedaya Masjid' })
this.props.addEvent(res.message);
// this.props.navigation.goBack();
}).catch((err) => alert(err));
I have another screen which contains different number of pictures like gallery i am uploading multiple picture to the gallery, the request is working fine with code below.
const data = new FormData();
data.append('name', 'avatar');
images.map((res, i) => {
data.append('fileData[]', {
uri: res.path,
type: res.mime,
name: `image${i}${moment()}`
});
})
const config = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: data,
};
fetch(`http://${Config.apihost}:${Config.port}/events/${this.state.item.id}/photos`, config)
.then((checkStatusAndGetJSONResponse) => checkStatusAndGetJSONResponse.json())
.then((response) => {
if (response.status && response.message.length > 0) {
var images = this.state.images;
response.message.map(file => {
images.push(`http:${Config.apihost}:${Config.port}/images/${file.id}`);
});
this.setState({ images });
}
}).catch((err) => { alert(err) });
I can't really see the difference between the two codes but the upper code giving me error.
I am testing on android
I am using the IP address instead of localhost (my others requests are working so thats out of equation)
None of the solution in this link worked
React Native fetch() Network Request Failed
Am I missing something?

In first code snippet you have written mime instead of type.
formData.append('image',{
uri:uri,
**mime:'image/jpeg**',
name:`image${moment()}`
})
it should be like below snippet
formData.append('image',{
uri:uri,
type:'image/jpeg',
name:`image${moment()}`
})

Related

Cannot upload file with FormData on React Native

I can't upload file with FormData to React Native. I am using react-native-document-picker and here is my code:
try {
const pickerResult = await DocumentPicker.pickSingle({
presentationStyle: 'fullScreen',
copyTo: 'documentDirectory',
type: [DocumentPicker.types.pdf],
mode: 'import',
});
setAccountStatement(pickerResult);
let data = new FormData();
data.append('file', {
uri: pickerResult.fileCopyUri,
type: pickerResult.type,
name: pickerResult.name,
fileName: pickerResult.name,
size: pickerResult.size,
});
console.log(data);
http
.post('url', data, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
}
};
Here's the example response I get from react-native-document-picker
{
"fileCopyUri": "file:///data/user/0/com.crust/files/497ed9ec-79fb-4bfb-81d1-74907f851c08/receipt_20220929065209.pdf",
"name": "receipt_20220929065209.pdf",
"size": 36036,
"type": "application/pdf",
"uri": "content://com.android.providers.media.documents/document/document%3A223934"
}
Please how do I go about this? I get
Error: Request failed with status code 415
from the server and I do not know what I am doing wrong.
So i managed to solve the issue after 2 days of tirelessly trying to figure it out , i managed to have two different solutions to the problem
1. Using Fetch API
const fd = new FormData();
fd.append('file', {
uri: pickerResult.fileCopyUri,
type: pickerResult.type,
name: pickerResult.name,
fileName: pickerResult.name,
size: pickerResult.size,
});
try {
const res = await fetch(
'url',
{
method: 'POST',
mode: 'no-cors',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'multipart/form-data',
},
body: fd,
},
);
console.log(res.status, res.statusText);
if (res.ok) {
console.log('Success');
} else {
console.log(await res.json());
}
} catch (error) {
console.error(error);
}
2. Downgrading Axios to "^0.24.0"
after i figured it out using the fetch api ,i was able to do a deeper research and found out that,
axios has a problem with the FormData() object, from version "^0.25.0"
, so i
downgraded my axios version to "^0.24.0"
and it worked like a charm including image upload using "FormData()"

Submit handler, React Axios: Post and Get in same handler

I am trying to create a web app that uploads file and attached the current user to the file model as a foreign key. For some reason the get request is being wiped, but it does initially get the needed information.
handleSubmit = (e) => {
e.preventDefault();
axios.get('http://127.0.0.1:8000/core/current_user/', {
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`,
}
}).then((user) => {
this.state.creator = user.data;
console.log(this.state.creator);
})
console.log(this.state.creator);
let form_data = new FormData();
form_data.append('creator', this.state.creator);
form_data.append('file', this.state.file);
form_data.append('title', this.state.title);
form_data.append('description', this.state.description);
axios.post('http://localhost:8000/core/posts/', form_data, {
headers: {
'Content-Type': 'multipart/form-data',
Authorization: `JWT ${localStorage.getItem('token')}`,
}
}).then(res => {
console.log(res.data);
}).catch(err => console.log(err))
};
The 1st console is returning the user information but the 2nd console returns null. Any help will be really appreciated.
Your then statement after the original get ends on line 11, and the rest of your code is outside of that.
With asynchronous code, the code outside of the then block will continue running while it's waiting for a response, so this.state.creator will not have been set yet. Then it will return to the code inside the then block once the promise resolves.
You need to move all of the second block of code inside the intial then block so it is only executed once a response to the original get request has returned:
handleSubmit = (e) => {
e.preventDefault();
axios
.get('http://127.0.0.1:8000/core/current_user/', {
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`,
},
})
.then((user) => {
this.state.creator = user.data;
console.log(this.state.creator);
let form_data = new FormData();
form_data.append('creator', this.state.creator);
form_data.append('file', this.state.file);
form_data.append('title', this.state.title);
form_data.append('description', this.state.description);
axios
.post('http://localhost:8000/core/posts/', form_data, {
headers: {
'Content-Type': 'multipart/form-data',
Authorization: `JWT ${localStorage.getItem('token')}`,
},
})
.then((res) => {
console.log(res.data);
})
.catch((err) => console.log(err));
});
};

How can I POST an image to DB via react native with the fetch API?

So I am trying to POST an image to a server via React Native and the fetch API.
fetch(`${API}/uploadAvatar`, {
method: "POST",
headers: {
Authorization: bearer,
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/json",
},
body: JSON.stringify({ file: result.uri }),
})
.then((response) => response.json())
.then((json) => {
console.log({ json });
// this console.log outputs:
// "The format of the file should be jpg, png, jpeg.",
})
.catch((err) => {
console.log({ err });
});
}
result returns this:
{
"cancelled": false,
"height": 1776,
"type": "image",
"uri": "file:///var/mobile/Containers/Data/Application/18F84F29-CB72-4615-A68F-A00422D9B119/Library/Caches/ExponentExperienceData/%2540heythere%252Fkeep-up/ImagePicker/959E8BDE-FCF4-40C6-AF18-8F9EA852760D.jpg",
"width": 1776,
}
Those are the calls on POSTMAN where you can see they work.
What am I doing wrong?
Your postman shows that you're using form-data to upload the image, but in your code you're simply making a JSON post call without sending any form-data. You need to create a new FormData instance, and append data to it. In your case, you want to send the result.uri with the key file, this can be done using formData.append('file', result.uri). Then you gotta send the formData instance as your body (with method as POST, in your case)
let formData = new FormData();
formData.append('file', result.uri);
fetch("api/SampleData", {
body: formData,
method: "post"
}).then((response) => response.json())
.then((json) => {
console.log({
json
});
})
.catch((err) => {
console.log({
err
});
});
You can post images to the server with the help of Form Data by creating a JSON object of the file path, file name, and file type and append the object into the Form Data instance with the parameter. The path of the file is Platform-specific therefore you have to add conditions for the path. Please refer to the code snippet.
let Data = new FormData();
Data.append('file',
{
uri: Platform.OS === 'android' ? result.uri: result.uri.replace('file://',''),
type: result.type,
name: result.uri.replace(/^.*[\\\/]/, '')
});
fetch("api/SampleData", {
body: Data,
method: "post",
headers: {'Content-Type': 'multipart/form-data'}
}).then((response) => response.json())
.then((json) => {
console.log({
json
});
})
.catch((err) => {
console.log({
err
});
});

Sending file and data with Fetch

I have an application in react. The state of my application is as follows
const [book, setBook] = useState({
title: '',
cover: {}
numberPages: 0,
resume: '',
date: date,
});
Cover prop contains a file. When I try to convert the state to json (JSON.stringify(book)) to send it with FETCH, the cover property is an empty object. How can I send this information correctly?
My on submit event form
let handleForm = (e) => {
data = JSON.stringify(book);
let info = {
method: 'POST',
body: data,
headers: {
'X-CSRF-TOKEN': header,
"Content-Type": "application/json",
"Accept": "application/json, text-plain, */*"
}
}
fetch('/books/add', info)
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.log(error));
e.preventDefault();
}
when you are sending files in fetch make sure u use the formdata
var data = new FormData()
data.append('title', book.title)
data.append('cover', book.cover)
fetch('/', {
method: 'POST',
body: data
})
Hope it works. If not please comment your code where you are making api call

Upload video in react-native

Is there a way to upload video to a server in react native?
I've looked into the react-native-uploader plugin on github, but it doesn't give any guidance on video uploads if it's even possible with that plugin.
Just use fetch for uploading
let formData = new FormData();
formData.append("videoFile", {
name: name.mp4,
uri: video.uri,
type: 'video/mp4'
});
formData.append("id", "1234567");
try {
let response = await fetch(url, {
method: 'post',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formData
});
return await response.json();
}
catch (error) {
console.log('error : ' + error);
return error;
}
Here is another answer, using rn-fetch-blob in RN 0.57.8.
postVideo = (video,url) => {
RNFetchBlob.fetch('POST',url, {
'content-type': 'multipart/form-data',
"Accept":"multipart/form-data",
'access-token': AuthToken.token, //token from server
},[
//the value of name depends on the key from server
{name: 'video', filename: 'vid.mp4', data: RNFetchBlob.wrap(video.uri) },
]).then(response => response.json())
.then(response => {
if (response.status === 'success') {
alert("Upload success");
this.props.navigation.navigate('publish');
} else {
alert(response.msg);
}})
.catch((err) => {
alert(err);
})
}
Yes, it is possible.
you have to be running React Native 0.45.0 or higher, which do support accessing videos from camera roll.
you have to receive reference to image/video access from camera roll by calling CameraRoll.getPhotos(params) (more on this in docs)
then, use RNUploader.upload(...) to send assets to your serve (you need to link lib before!)

Categories

Resources