I am running my android app with ionic cordova run android, and doing a HTTP get to a local ip address:
this.http.get('http://192.168.2.124:8080')
.pipe(map((response: any) => {
alert(response);
return response;
}),
catchError(map((error: Response | any) => {
alert(error);
console.error('API error: ', error);
return error;
})));
However, nothing happens at all, no errors either.
Note:
replacing the host with something I deployed on the cloud works just fine;
using the phone's web browser to navigate to that endpoint also works.
I'm lost: is there a android or ionic configuration I'm missing to allow this?
Thank you
Related
Relevant modules used:
"expo": "~46.0.9"
"axios": "^0.27.2"
I'm trying to fetch some data, everything works just fine on iOS devices but the problem comes when using an Android, the network fails for some reason:
Android Running app on sdk_gphone64_arm64
[AxiosError: Network Error]
Here's the line of code that causes it:
const { data } = await axios.get('http:<my IP or 'localhost'>:<port>/endpoint');
Any ideas on how to fix it?
The solution for this was that Axios didn't really need my real IP address. It needed the IP that expo gives you when you start the metro bundler.
So instead of:
axios.get('http:<my IP or 'localhost'>:<port>/endpoint')
I changed it for:
axios.get('http:192.168.100.20:<port>/endpoint')
Now it is working.
I am getting a Network request failed when trying to fetch from localhost in ReactNative for both android and ios devices.
I've tried following previous solutions but nothing seemed to work for me. I followed this tutorial: https://revs.runtime-revolution.com/connecting-react-native-to-localhost-65e7ddf43d02
For iOS:
I edited the info.plist and added the following code and reinstalled the app on my simulator but it still didn't work.
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>localhost</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
</dict>
For Android:
I used my IP instead of 'localhost' for my fetching URL but it still didn't work. I also made configurations to AndroidManifest.xml following the steps in the tutorial but it still doesn't work.
Any other solutions???
PS. I am using a Macbook. My REST API is using SQL database and asp.net core. I am trying to fetch a json.
Error: Network Request Failed
Fetch code:
async getProjects1() {
const response = await fetch('https://127.0.0.1:5001/api/projects');
const data = await response.json();
this.setState({ projects: data, loading: false }, function(){console.log(this.state.projects)});
};
Your error message says that there is unhandled promise rejection, so i'd advise adding error handling as:
async getProjects1() {
try {
const response = await fetch('https://127.0.0.1:5001/api/projects');
const data = await response.json();
this.setState({ projects: data, loading: false }, function(){console.log(this.state.projects)});
} catch (err) {
console.log(err)
}
}
and this issue may be resolved, or you at least might get clearer error message.
I solved the issue. The error was not because of react native but from my asp.net core API. Basically, I just needed to change my code in the launchsettings.js in the Properties folder from "applicationUrl": "https://localhost:5001;http://localhost:5000" to "applicationUrl": "http://localhost:5000"
This solved the issue and fetching from localhost in react native worked without any further issues. This stack question helped me figure this out: How to fix network error in react-native when access localhost api
These solutions did not work.
What did work:
Download ngrok (https://ngrok.com/), signup, and connect your account. ngrok creates a private https localhost tunnel.
Setup - https://dashboard.ngrok.com/get-started/setup
Unzip to install ngrok:
unzip /path/to/ngrok.zip
Connect your ngrok account (Non functioning example auth token):
ngrok config add-authtoken 2ySPR5UeS3Fjf5YAblNRe7ZcV1o_9sdf2SDFGHjEQaOCE6xEi
Use the command (with your port number):
ngrok http 8080
Once ngrok is online, replace your localhost API address:
http://localhost:8080
http://127.0.0.1:8080
http://192.168.0.100:8080
With the forwarding web address (Non functioning example address):
https://ebda-61-137-45-130.ngrok.io
I've used ngrok for testing APIs on a variety of networks without issue. So far its the only foolproof method I've found for testing APIs using localhost.
I am new to react native, I want to make a VPN client app for Android and IOS.
VPN protocol should be IPSec or IKEv2 or any other. I have tried these:
1. OpenVPN
node-openvpn and openvpn-bin but no luck
const openvpnmanager = require('node-openvpn'); **
const opts = {
host: '127.0.0.1', // normally '127.0.0.1', will default to if undefined
port: 1337, //port openvpn management console
timeout: 1500, //timeout for connection - optional, will default to 1500ms if undefined
logpath: 'log.txt' //optional write openvpn console output to file, can be relative path or absolute
};
const auth = {
user: 'vpnUserName',
pass: 'vpnPassword',
};
const openvpn = openvpnmanager.connect(opts)
// will be emited on successful interfacing with openvpn instance
openvpn.on('connected', () => {
openvpnmanager.authorize(auth);
})
2. react native open settings
react-native-device-setting and react-native-open-settings in which they have showed to programmatically open android phone settings like:
install package: npm install react-native-device-settings --save
usage:
import DeviceSettings from 'react-native-device-settings';
DeviceSettings.open(); // Open settings menu
DeviceSettings.app(); // Open app settings menu
DeviceSettings.wifi(); // Open wifi settings menu
but there is no method to open up the VPN Settings and configure VPN. 47306057 has also asked the same problem
i need some direction or way to solve this. is there a library or something that i should use or make a VPN app in android studio and then import the aar file here. will it work?
Can anyone help me out in this? Thanks
I am building a React Native mobile application that is using a Laravel backend, currently running on localhost:8000. When making a fetch request from an Android device to my server, my application gets the following error logs:
My code is below:
export default class App extends Component {
login() {
fetch('http://localhost:8000/api/establishments/get')
.then((response) => response.json())
.then((responseJson) => {
console.log('success!');
})
.catch((error) => {
console.error(error);
});
}
render() {
return (
<TouchableOpacity activeOpacity={.5} onPress={() => this.login()}>
<Text>Sign In</Text>
</TouchableOpacity>
);
}
}
When I copy and paste the exact route into my browser, the server responds successfully and completely as expected. I believe it is an issue with network permissions from my application? I have only just began learning React Native a week ago and would appreciate any help at all.
iOS runs in a simulator while Android runs in an emulator.
Emulator emulates a real device, while simulator only imitates a device.
Therefore localhost on Android points to the emulated Android device instead of the machine where your server runs.
You should change localhost in yours request paths with the IP address of your machine.
More details at: https://github.com/facebook/react-native/issues/10404#issuecomment-267303151
I suspect that 127.0.0.1 or localhost will point to the emulator itself in your computer where the server is currently running. Try replacing 127.0.0.1 / localhost with 10.0.2.2 if you are on AVD or 10.0.3.2 if you are on Genymotion or with your computer's actual IP address. In addition, you should also make sure that your android app can use internet. You can do that by adding
<uses-permission android:name="android.permission.INTERNET" />
in your AndroidManifest.xml.
Founded solution for Laravel and react native (Physical device)
open cmd run ipconfig copy ipv4 address for example my ipv4 address is 192.168.43.235
Connect same network for laptop and physical device or open hotspot and connect same network
Now run command start laravel backend php artisan serve --host=192.168.43.235 --port=8000
change api url from react native api service
apiServise.js
import axios from 'axios';
const api_url = 'http://192.168.43.235:8000';
export const getCategories = request =>
axios
.get(api_url + '/api/categories', {
params: request || {},
})
.then(response => response.data);
homescreen.js
import {getCategories} from '../services/ApiService';
async fetchCategories() {
await getCategories()
.then(response => {
this.setState({
dataCategories: response
});
})
.catch(error => {
console.log(error);
});
}
Now run command start react native app react-native run-android
that is all...now api request working fine.
Change http://localhost:8000/api/establishments/get localhost with, which can your emulator reach generally 10.0.2.2 ;) have phun.
I am developing an app using Phonegap Build for a customer that has chosen not to use the Google Play Store. Instead, they are opting to have me privately host the APK files for the app.
I am trying to develop a way to dynamically check my server every time the app is launched to check to see if there is an update and if there is, to download and install that update.
I do an ajax request to my server to check for the latest file, I then return the latest version number and URL of the file on AWS to my frontend. If the file version is greater than the current app version, I want to update.
Here's the code I have right now using the FileTransfer and Web Intent plugins for Phonegap Build:
$.ajax
type: 'GET'
dataType: 'json'
url: "#{baseUrl}/v2/update"
data:
app_token: 'fubar'
success: (data) =>
window.downloadApkAndroid(data)
window.downloadApkAndroid = (data) ->
fileURL = "cdvfile://localhost/persistent/#{data.filename}"
fileTransfer = new FileTransfer
uri = encodeURI(data.download_url)
fileTransfer.download uri, fileURL, ((entry) ->
alert 'download complete: ' + entry.fullPath
promptForUpdateAndroid entry
return
), ((error) ->
console.log 'download error source ' + error.source
console.log 'download error target ' + error.target
console.log 'upload error code' + error.code
alert "#{error.code} + #{error.source} + #{error.target}"
return
), false, {}
return
window.promptForUpdateAndroid = (entry) ->
alert entry
window.plugins.webintent.startActivity {
action: window.plugins.webintent.ACTION_VIEW
url: entry.toURL()
type: 'application/vnd.android.package-archive'
}, (->
), ->
alert 'Failed to open URL via Android Intent.'
console.log 'Failed to open URL via Android Intent. URL: ' + entry.fullPath
return
return
Nothing happens when I launch the app, though. I am returning a newer version from the first Ajax request and the success method is being called. But nothing seems to happen after that. Can anyone tell me any better methods of doing this or what I'm doing wrong here?
Have you considered using the Cordova Hot Code Push plugin, which would allow you to update your application's www folder (the app views, JS, CSS, any images etc) without having to do a Google Play update. This method would allow you to ship a version of your application in the apk, and periodically get updates from a server without having to build boilerplate file fetching code yourself.