Network request failed while using Fetch in react-native - react-native

I am getting the following error when i try to fetch API from my local server
TypeError: Network request failed
at XMLHttpRequest.xhr.onerror (blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:15823:18)
at XMLHttpRequest.dispatchEvent (blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:17900:39)
at XMLHttpRequest.setReadyState (blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:17655:20)
at XMLHttpRequest.__didCompleteResponse (blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:17482:16)
at blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:17592:47
at RCTDeviceEventEmitter.emit (blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:3478:37)
at MessageQueue.__callFunction (blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:2384:44)
at blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:2154:17
at MessageQueue.__guardSafe (blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:2346:11)
at MessageQueue.callFunctionReturnFlushedQueue (blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:2153:14) {stack: TypeError: Network request failed
at XMLHttpRe…081/9b6428f5-4e65-45a0-9490-3852c365f0df:2153:14),
message: Network request failed}
I am accessing the APi from my client as follows
const apiURL = "192.168.1.5:3000/api/";
fetch(apiURL + '/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: this.props.username,
password: this.props.password
})
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
})
.catch((error) => {
console.log(error);
});
I am running the app on my actual device which runs in android 7.0.Both my laptop and mobile are connected on the same Wi-Fi. I check my manifest file and yes Internet permission was enabled. I am not sure what i am doing wrong.

Related

Network Error While making axios call with Form Data

We have an application where we need to upload documents or images:
react: 17.0.2
react-native: 0.68.2
axios: 1.3.2
While making web service call using axios, we are getting Network Error in both iOS and Android.
Same API is working in web and through Postman.
Code (Same code is working fine with Json data.)
try {
var formData = new FormData();
formData.append('file', fileUpload);
const obj = { hello: "world" };
formData.append('param', JSON.stringify(obj));
const response = await axios({
method: 'post',
url: 'https://xxxxxxxxxxx.com/fr_webservice/file/doUpload',
data: formData,
headers: {
'x-auth-token': authData.token,
Accept: "application/json ,text/plain, */*",
"Content-Type": "multipart/form-data"
},
});
console.log("[Form Data Response]: ", response);
} catch (error) {
console.log("[Form Data Error]: ", error);
}
"AxiosError: Network Error
at XMLHttpRequest.handleError (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:191293:16)
at XMLHttpRequest.dispatchEvent (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:26337:27)
at XMLHttpRequest.setReadyState (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:25607:20)
at XMLHttpRequest.__didCompleteResponse (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:25417:16)
at http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:25543:47
at EventEmitter.emit (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:1731:37)
at MessageQueue.__callFunction (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:2533:31)
at http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:2302:17
at MessageQueue.__guard (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:2492:13)
at MessageQueue.callFunctionReturnFlushedQueue (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:2301:14)"

LOG [TypeError: Network request failed]

I am new to react native. Every time i try to fetch i get this error
[TypeError: Network request failed]
below is the code:
fetch("http://192.168.20.137:3000/posts", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(memberID),
})
.then((res) => res.json())
.then((data) => Alert.alert(data))
.catch((err) => console.log(err));
}; ```
Add these lines of code inside AndroidManifest.xml
<application
....
....
android:usesCleartextTraffic="true">
Then, try to run your code in a real physical device, instead of emulator,
to run on physical devices - connect your usb and try to run npx react-native run-android

Android: Network Request Failed when trying to upload image with fetch

I'm trying to upload an image from storage to a restful API but I keep getting Network Request Failed on Android (which means the request doesn't even go through), haven't checked on iOS because I don't need that part yet. API is already working and has been tested with Postman.
The React Native code is:
body.append('vehicles',{
resource_id: 2,
resource: 'vehicles',
cat_file_id: fileId,
active: 1,
vehicles: photo, //<- photo value below
name: 'vehicles',
type: 'image/jpeg'
})
fetch(`${BASE_URL}/files`, {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
Accept: "*/*",
Authorization: 'Bearer '+auth
},
body: body
}).then(response => response.json())
.then(response => {
console.log('IMAGE RESPONSE', response)
})
.catch(error => console.log('ERROR', error))
The photo value looks like file:///storage/emulated/0/DCIM/...
The response:
ERROR TypeError: Network request failed
at XMLHttpRequest.xhr.onerror (fetch.umd.js:473)
at XMLHttpRequest.dispatchEvent (event-target-shim.js:818)
at XMLHttpRequest.setReadyState (XMLHttpRequest.js:574)
at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:388)
at XMLHttpRequest.js:501
at RCTDeviceEventEmitter.emit (EventEmitter.js:189)
at MessageQueue.__callFunction (MessageQueue.js:436)
at MessageQueue.js:111
at MessageQueue.__guard (MessageQueue.js:384)
at MessageQueue.callFunctionReturnFlushedQueue (MessageQueue.js:110)
On Postman the request looks something like this:
Already tried:
Removing Accept header
Changing Accept value to 'application/json'
Removing file:// from the image url
Added android:usesCleartextTraffic="true" to the manifest
Already checked:
No values are null or undefined
There is a working internet connection, all other network requests on the app are working fine
The Auth is correct
React Native version is 0.61.5
I found one missing line in your code let formData = new FormData();. but not sure is that the exact issue here.
By the way here is a sample working code from one of my project, and I customized it with your context.
Add your authentication
replace ImageURI with image path and URL_SAVE_IMAGE endpoint url
const newImage = {
resource_id: 2,
resource: 'vehicles',
cat_file_id: 1,
active: 1,
vehicles: ImageURI,
name: "my_photo.jpg",
type: "image/jpg",
};
let formData = new FormData();
formData.append("vehicles", newImage);
return fetch(URL_SAVE_IMAGE, {
method: 'POST',
headers: {
"Content-Type": "multipart/form-data"
},
body: formData
}).then(response => response.json());
it should work!
What is your fetch(${BASE_URL}/files` backend server .. This usually happens when trying to connect to the backend api on the localhost machine.. Even if you use the IP address of the localhost, it still persists, so it is better to use online server for testing or just use ngrok(https://ngrok.com/) to serve your backend localhost via internet.
in gradle.properties change the flipper version to 0.47.0
try with Xhr, it's working as expected!
const URL = "ANY_SERVER/upload/image"
const xhr = new XMLHttpRequest();
xhr.open('POST', url); // the address really doesnt matter the error occures before the network request is even made.
const data = new FormData();
data.append('image', { uri: image.path, name: 'image.jpg', type: 'image/jpeg' });
xhr.send(data);
xhr.onreadystatechange = e => {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status === 200) {
console.log('success', xhr.responseText);
} else {
console.log('error', xhr.responseText);
}
};
Nothing worked for me except using the Expo FileSystem uploadAsync
uploadImage = async ({ imageUri } }) => FileSystem.uploadAsync(
apiUrl,
imageUri,
{
headers: {
// Auth etc
},
uploadType: FileSystem.FileSystemUploadType.MULTIPART,
fieldName: 'files',
mimeType: 'image/png',
});
Note - imageUri in format of file:///mypath/to/image.png
Happy days!

fetch error network on react native but working on postman

I'm currently developping a react-native app. Working on the login part,
I successfully made my call on postman with the right return but when fetching through react-native android client I get absolutly no return when calling the heroku server or even a network failed error when running the server locally.
What am I doing wrong ? I got absolutly no logs back from the code under.
const payloadJson = JSON.stringify({
email: 'julien#hypecode.com',
password: 'password',
})
fetch('https://alsatoju-dev.herokuapp.com/login', {
method: 'POST',
body: payloadJson,
headers: {
Accept: '*/*',
'Content-Type': 'application/json',
},
}).then((response) => {
console.log(response)
return response.json()
})
.then((res) => console.log(res))
.catch((err) => console.log(err))

React Native - Can't get data from asp.net web api

I'm building an app using React Native with Expo and an ASP.Net Web API.
I'm using two computers: one I published the Web API on it and using it as a server which has the IP 192.168.1.9 ,
and the other one with IP 192.168.1.6 I'm using for developing.
The problem is when I ping the server computer I get a reply and when I use postman I get the data I requested,
but when I run the app using Expo on my Android Phone, the request enters the catch and returns an error.
Here is the code:
var url = 'http://192.168.1.9/trainlast/api/Login';
fetch(url,
{
method: 'GET',
})
.then(response => { response.json(); })
.then(users => {
this.setState({ allUsers: users });
})
.catch(error => console.error('Error getting users :: ', error));
I have tried everything I could possibly think of, but no use.
Can someone tell me what the problem is? thank you .
You can configure Accept and Content-Type of headers.
And get the correct value for the object.
var url = 'http://192.168.1.9/trainlast/api/Login';
fetch(url,
{
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
}
})
.then((response) => response.json())
.then(res => {
this.setState({ allUsers: res.Username });
})
.catch(error => console.error('Error getting users :: ', error));