React Native fetch fail - react-native

When I use fetch() method to make get request, it failed with "TypeError: Network request failed". It's weird that it sometimes failed but sometimes succeeded. I have tried the solution here: React Native fetch() Network Request Failed, but it didn't work for me. By the way, I am using Android.
This is my code :
try {
let url = "http://140.116.245.229:3000/GetCarsJson";
let data = await fetch(url);
let toJson = await data.json();
} catch(err) {
throw err;
}
This is the error message :
enter image description here

You should ensure your devices/simulator/emulator can connect to this endpoint
If you use Android emulator, you can refer this link How to connect to a local server from an android emulator?

Related

Playing an audio file with source => {uri: 'remote-file-path'} not working - React Native (expo)

I keep getting this error when i try to play an audio from my local backend or an already uploaded audio from a site.
No matter what file format, this is what I get and this only happens with ios
error: Possible Unhandled Promise Rejection (id: 0): Error: The server is not correctly configured. - The AVPlayerItem instance has failed with the error code -11850 and domain "AVFoundationErrorDomain". Error: The server is not correctly configured. - The AVPlayerItem instance has failed with the error code -11850 and domain "AVFoundationErrorDomain".
error image
const player = new Audio.Sound();
player.loadAsync({ uri: url }, initialStatus).then(() => {
player.playAsync().then((playbackStatus) => {
if (playbackStatus.error) {
handlePlaybackError(playbackStatus.error);
}
});
});
After adding more error handling, I found out the error comes from loadAsync and it only happens when I try to play an audio from my local backend server. (ex: http://127.0.0.1:8000/media/audios/2021/08/08/27/21/filename.mp4)
It would be really great if I could get help on this, thanks in advance!
Update: Provided more code
So I found out that the that warning was being generated and preventing my audio files from playing because they are stored in my local server and for some reason the expo Audio.Sound object had an issue loading them, so I had to install expo-file-system, use the FileSystem to read download the file and use the uri produced from the download.
Example:
import * as FileSystem from 'expo-file-system';
const splitUrl = url.split('/');
const lastItem = splitUrl[splitUrl.length - 1];
const { uri } = await FileSystem.downloadAsync(
url,
FileSystem.documentDirectory + lastItem
);
const source = { uri: uri }; //the source you provide to the loadAsync() method
loadAsync() returns a Promise, so you have to await it.
If this is not the problem you have to provide more code, please.
Here's the documentation, so use it like this:
const sound = new Audio.Sound();
try {
await sound.loadAsync(require('./assets/sounds/hello.mp3'));
await sound.playAsync();
// Your sound is playing!
// Don't forget to unload the sound from memory
// when you are done using the Sound object
await sound.unloadAsync();
} catch (error) {
// An error occurred!
}
And here's a simple snack I made, it works for me, you might want to consider error handling using try-catch:
Snack example

Display Wifi list in React Native

I need to display available WiFi network's list.
By using npm install react-native-wifi-reborn --save I can get the list but only in the log. How can I display the Wifi List as text from the console log.
I tried this code.
But got this error
Error: Exception in HostFunction: Malformed calls from JS: field sizes are different.
As per the docs,loadWifiList() returns Promise<Array<WifiEntry>>, so you should either use async/await or .then to access the result.
You could try something like this
const getWifiList = async() => {
let wifiList = await wifi.loadWifiList(); //wifiList will be Array<WifiEntry>
console.log('wifi list',wifiList);
}

React Native: Network error when using axios on local server

I'm new to react-native, I want to fetch some data from my local laravel server, but I fire the mobx action I get the following errors:
Network Error
[Unhandled promise rejection: Error: Network Error]
This is my mobx action (I'm using flow, similar to async/await), I get 'fire' log but after that I get the error above:
listProducts = flow( function*(payload)
{
console.log('fire');
try
{
let response = yield axios.get('http://192.168.1.39:8000/api/products', { params: payload });
this.posts = response.data;
this.pagination = response.data.pagination;
console.log(response);
//return response;
}
catch (error)
{
console.error(error);
throw error;
}
});
As you can see I'm using my local IP instead of localhost, I'm also testing my app on my android device using EXPO connected to the same network as my dev laptop.
Ciao, I can't see errors on your code. Try to follow this guide to handle Unhandled promise rejection. Could help you to find a clue.
In brief the guide suggest to use axios interceptors:
axios.interceptors.response.use(
response => response,
error => {}
)

React Native with axios - Network error calling localhost with self signed https endpoint

I created service in Visual Studio with Conveyor extension to make it accessible in local network. I installed certificate on my Android device so there is green padlock when calling it in browser and service works fine.
However when calling it from React Native app with axios then i get Network error.
That's my code:
const fetchData = async () => {
console.log('url', `${Settings.API_URL}/location/GetDataByMyIp`);
try {
const result = await axios(
`${Settings.API_URL}/location/GetDataByMyIp`,
);
console.log('result', result);
ipData = {
city: result.data.city,
longitude: result.data.longitude,
latitude: result.data.latitude,
};
} catch (e) {
console.log('error', e);
}
};
await fetchData();
In console i see:
url https://192.168.1.14:45455/api/location/GetDataByMyIp
error Error: Network Error
at createError (path_to_app\node_modules\axios\lib\core\createError.js:16)
at EventTarget.handleError (path_to_app\node_modules\axios\lib\adapters\xhr.js:83)
at EventTarget.dispatchEvent (path_to_app\node_modules\event-target-shim\dist\event-target-shim.js:818)
at EventTarget.setReadyState (path_to_app\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:575)
at EventTarget.__didCompleteResponse (path_to_app\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:389)
at path_to_app\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:502
at RCTDeviceEventEmitter.emit (path_to_app\node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:189)
at MessageQueue.__callFunction (path_to_app\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:425)
at path_to_app\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112
at MessageQueue.__guard (path_to_app\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:373)
I tried to add this line to AndroidManifest.xml application tag but still have the error
android:usesCleartextTraffic="true"
Some solutions say about adding as 2nd parameter to axios, but it doesn't work with React Native.
new https.Agent({
rejectUnauthorized: false,
});
I tried to call some other service from the internet and then error was gone.
Is there some solution to this? I haven't found anything more. My last idea is to host service on Azure so I'll have properly signed SSL, but i guess it has to be a way to run it locally.
Edit: It works through http

Titanium App Crash With a Simple Get Request - Uncaught TypeError

I am trying to fetch data from a simple get request using Titanium.Network.HTTPClient
Here is the code
var url = "http://www.appcelerator.com"; //Here i have my get api URL, i have also tried replacing the url with google.com
var client = Ti.Network.createHTTPClient({
// function called when the response data is available
onload : function(e) {
Ti.API.info("Received text: " + this.responseText);
alert('success');
},
// function called when an error occurs, including a timeout
onerror : function(e) {
Ti.API.debug(e.error);
alert('error');
},
timeout : 5000 // in milliseconds
});
// Prepare the connection.
client.open("GET", url);
// Send the request.
client.send();
But the app is crashing with error Uncaught TypeError: Cannot read property 'extendModel' of undefined, I am not using any model, It is a new project with the above mentioned code, nothing more.
Here is the screenshot of error
Please help!
EDIT
Configuration details:
Titanium Command-Line Interface, CLI version 5.0.13
Titanium SDK
version 6.0.4.GA
Node version v4.8.2
Please let me know if any further details required,