axios giving [AxiosError: Network Error] in react native - react-native

i am new to react native and i am trying to submit a api using axios in react native but i am getiign [AxiosError: Network Error] i dont know what this is or how i can fix this
function getdata() {
const Data = {
babyname: babyname,
password: name,
email: email,
phone: nuber,
period: mydate,
};
console.log(Data);
axios({
method: 'POST',
url: 'http://127.0.0.1:8000/api/details/',
data: Data,
})
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
i used the default inspect elemt in react native and have network tab opened

I think the problem is from Ip that you are trying to get connected
it seems that you are using an android emulator, so 127.0.0.1 is not the IP that runs in Postman
if 127.0.0.1 is your localhost, changing that to 10.0.2.2 might fix your problem
axios({
method: 'POST',
url: 'http://10.0.2.2:8000/api/details/',
data: Data,
})

Related

React native Expo project, Fetch the API will get [TypeError: Network request failed], but the others api can work

When I fetch the api in React native Expo project will get [TypeError: Network request failed].
I have try to fetch other API, it can get data success.
And also try to fix by this question but didn't work for me.
(Also tried this React Native fetch() Network Request Failed)
Is API's problem?
My code like:
const val = { uId: 'molly', pwd: '123', id: '1' }
const url = 'https://c........com.tw:8899'
let header = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(val),
}
fetch(`${url}/auth/login`, header)
.then((r) => r.json())
.then((d) => {
if (d.code === 0) {
console.log(d.data)
} else {
console.log('MSG', d.msg)
}
})
.catch((err) => console.log(err))
And I have try this, it can work. (So is not the network problem.)
fetch('https://randomuser.me/api/')
.then((r) => r.json())
.then((d) => {
console.log('ok')
})
.catch((err) => console.log(err))
Thanks for any suggestion.
I found the problem is about ssl.
Should use this package to deal with
react-native-ssl-pinning
https://www.npmjs.com/package/react-native-ssl-pinning

React Native Axios Network Error but works fine on postman client

I'm trying to get axios working on a react native project to reach a backend but I am getting the Network Error issue that I just can't seem to debug.
const searchApi = async () => {
try {
let res = await axios.get('https://product.company.com/api/documents/invoices');
console.log(res);
} catch (err) {
console.log(err);
}
}
So if I was to do a get request to the example url provided via Thunder Client or Postman Client, I get the appropriate response of
{
"status": "401 error",
"message": "Token not found."
}
But when done through axios, I seem to get a network error. I'm a little unsure how I can debug this too to get more error logs.
Try with below code:
Replace with Your URL
var config = {
method: 'get',
url: 'https://reqres.in/api/users?page=1',
headers: {
'Content-Type': 'application/json'
}
};
axios(config).then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
It's not a network error but an unauthorized error. You need to pass some authenticated token in the header.

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!

React Native fetch returns 404 but postman does 200 ok

I am integrating Spotify web api into react native application. I have problem with React Native fetch. When I call the api inside Postman, I get 200 response code but if I run it inside emulator(react native) I get 404 error code. I also wrote the fetch request inside chrome console and it works good but in react native it is not working.
The code that I am running:
let response = await fetch(`https://api.spotify.com/v1/browse/featured-playlists?locale=en_US&country=US`, {
method: 'GET',
headers: {
'Accept': 'application/json;charset=utf-8',
'Content-Type': 'application/json;charset=utf-8',
'Authorization': 'Bearer BQDT3_xtYLyIsGaqhoTM42Z-k3ijs-hFbzIG89basd7Me-kL4SUWSLgQrxWN3b13DiqU6THfr4VH4Z7klnc'
}
});
console.log("response",response.status)
I tried the following code in React Native v. 0.58.6
async componentDidMount() {
let spotifyApiUrl = "https://api.spotify.com/v1/browse/featured-playlists?locale=en_US&country=US";
let fetchSettings = {
method: 'GET',
headers: {
'Accept': 'application/json;charset=utf-8',
'Content-Type': 'application/json;charset=utf-8',
'Authorization': 'Bearer BQDT3_xtYLyIsGaqhoTM42Z-k3ijs-hFbzIG89basd7Me-kL4SUWSLgQrxWN3b13DiqU6THfr4VH4Z7klnc'
}
};
fetch(spotifyApiUrl, fetchSettings)
.then( (response) => response.json() )
.then( (responseJson) => {
console.log(JSON.stringify(responseJson));
})
.catch((error) => {
console.log(error);
});
}
With the following console output:
{"error":{"status":401,"message":"The access token expired"}}
Have you tried plugging in your actual device to see if it is an emulator issue?
Remember to forward tcp ports on adb before running "react-native run-android" if you use a real device
adb reverse tcp:8081 tcp:8081
react-native run-android

How to check if body in fetch POST has sent to API in react native?

I am building a react native app and got this following error. I want to send inputted message, email, and name to API, but it's not showing any result in API.
Here is the code:
fetch('localserverusingIPaddress', {
method: 'POST',
headers: {
"Content-Type": "application/json",
'Accept': 'application/json',
},
body: JSON.stringify({
name: this.state.name,
email: this.state.email,
message: this.state.message,
}),
})
.then((response)=> {console.warn(response.json())})
//{
// if (response.status){
// return response.json();
// }
// console.warn(response.json())
// return response.json();
//})
//console.warn(response);
//response.json()
//console.warn(JSON.parse(response))})
.then((responseData)=>{
this.showAlert();
console.warn(responseData);
return responseData;
})
.catch((error) => {
console.warn(error);
});
However, when I try to check the inputted texts in iOS
simulator, it's showing the value. It's also showing the values when I post data to API directly with postman. So I start to think that the body was failed to pass to API.
Can anyone please tell me why is this happening and how to fix this? Thank you so much, I'm facing this problem for several weeks...
First step is to make sure if your iOS simulator is actually able to make requests to your localhost or not. If it can't reach your local network, it must throw some kind of connectivity error. However, from your comment above, it seems that is not an issue.
Try this code:
let url = 'localserverusingIPaddress';
let requestObject = {
name: this.state.name,
email: this.state.email,
message: this.state.message
};
try {
let response = await fetch(url, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(requestObject)
});
responseJson = await response.json();
console.log(responseJson);
} catch (error) {
console.error(error);
}
Try this and see what is the logged output.
Easiest way to see if the request has actually reached your API is from the API end itself. Your server must have some sort of event logging implemented. See what happens there when you make a request from Postman and compare its output with what happens when you make a request from the app.