React Native: request api on http server not work - laravel

I tried to fetch api from laravel server in my react native app
I launched laravel servers with php artisan serve --host=0.0.0.0 so i can access to my api route with http://myIp:8000/myProject/api/; in this project i have route
Route::get('/test', function(){
return response()->json([
'data' => 'test'
]);
});
I already tested http://myIp:8000/myProject/api/test in my mobiles device's browser and i got the json data;
So in my react native i installed axios configured like this:
axios.create({
baseUrl: base_url_api,
headers: {
Accept: 'application/json',
'Content-type': 'application/json'
}
})
And i fetch the api like this axios.get("http://myIp:8000/myProject/api/test") but it throw error Error Network;
So i tried with axios.get("https://jsonplaceholder.typicode.com/todos/1") and i got the json data from jsonplaceholder;
I already set android:usesCleartextTraffic="true" on my AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".MainApplication"
android:label="#string/app_name"
android:icon="#mipmap/ic_launcher"
android:roundIcon="#mipmap/ic_launcher_round"
android:allowBackup="false"
android:theme="#style/AppTheme"
android:usesCleartextTraffic="true"
>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
but it not work;
here my package.json dependecies
"dependencies": {
"axios": "^0.21.4",
"react": "17.0.2",
"react-native": "0.65.1",
"react-native-elements": "^3.4.2",
"react-native-gesture-handler": "^1.10.3",
"react-native-paper": "^4.9.2",
"react-native-reanimated": "^2.2.2",
"react-native-safe-area-context": "^3.3.2",
"react-native-screens": "^3.7.2",
"react-native-vector-icons": "^8.1.0"
},
"devDependencies": {
"#babel/core": "^7.15.5",
"#babel/runtime": "^7.15.4",
"#react-native-community/eslint-config": "^3.0.1",
"babel-jest": "^27.2.2",
"eslint": "^7.32.0",
"jest": "^27.2.2",
"metro-react-native-babel-preset": "^0.66.2",
"react-native-codegen": "^0.0.7",
"react-test-renderer": "17.0.2"
},
my react native cli version
react-native --version
react-native-cli: 2.0.1
react-native: 0.65.1

I know it's stupid but I used wrong properties name for axios configuration,
instead baseURL I set baseUrl
axios.create({
baseURL: base_url_api,
headers: {
Accept: 'application/json',
'Content-type': 'application/json'
}
})
Posted on behalf of the question asker

Related

Nativescript Android keeps crashing

I am creating a nativescript application and when I try to debug on my android device (connected via usb) the app opens the splash screen and immediately crashes without any errors shown in the console.
I open another terminal and use adb logcat *:W --pid=15820 to get error output (warnings and above) and all I see is failures to connect. These occur after the app crashes and keep repeating every second. What else can I do to find out why my app is crashing? It runs fine on an ios emulator.
06-29 15:45:30.127 15820 15820 E adbd : failed to connect to socket 'localabstract:com.mycompany.myapp-livesync': Connection refused
06-29 15:45:31.136 15820 15820 E adbd : failed to connect to socket 'localabstract:com.mycompany.myapp-livesync': Connection refused
06-29 15:45:32.141 15820 15820 E adbd : failed to connect to socket 'localabstract:com.mycompany.myapp-livesync': Connection refused
package.json
{
"nativescript": {
"id": "com.mycompany.myapp",
"tns-ios": {
"version": "5.4.2"
},
"tns-android": {
"version": "5.4.0"
}
},
"description": "My Mobile App",
"license": "SEE LICENSE IN <your-license-filename>",
"repository": "https://github.com/...",
"scripts": {
"lint": "tslint \"src/**/*.ts\"",
"clean": "find ./src -name '*.js' -delete",
"debug:android": "adb logcat *:W --pid=15820"
},
"dependencies": {
"#angular/animations": "8.0.0",
"#angular/common": "8.0.0",
"#angular/compiler": "8.0.0",
"#angular/core": "8.0.0",
"#angular/forms": "8.0.0",
"#angular/http": "8.0.0-beta.10",
"#angular/platform-browser": "8.0.0",
"#angular/platform-browser-dynamic": "8.0.0",
"#angular/router": "8.0.0",
"#ngxs/store": "^3.4.3",
"#turf/bearing": "^6.0.1",
"#turf/distance": "^6.0.1",
"nativescript-angular": "^8.0.0",
"nativescript-camera": "^4.5.0",
"nativescript-geolocation": "5.1.0",
"nativescript-google-maps-sdk": "2.7.0",
"nativescript-plugin-firebase": "^9.0.1",
"nativescript-social-share": "^1.5.2",
"nativescript-theme-core": "1.0.4",
"nativescript-urlhandler": "1.2.3",
"reflect-metadata": "0.1.13",
"rxjs": "6.5.2",
"tns-core-modules": "^5.4.3",
"zone.js": "^0.8.4"
},
"devDependencies": {
"#angular/compiler-cli": "8.0.0",
"#ngtools/webpack": "8.0.3",
"nativescript-dev-typescript": "^0.10.0",
"nativescript-dev-webpack": "0.24.1"
},
"readme": "My App"
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="__PACKAGE__"
android:versionCode="1"
android:versionName="1.0">
<supports-screens
android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:xlargeScreens="true"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:name="com.mycompany.myapp"
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="My Mobile App"
android:theme="#style/AppTheme">
<uses-library android:name="org.apache.http.legacy" android:required="false"/>
<meta-data android:name="firebase_analytics_collection_enabled" android:value="false" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/nativescript_google_maps_api_key" />
<activity
android:name="com.tns.NativeScriptActivity"
android:label="#string/title_activity_kimera"
android:configChanges="keyboardHidden|orientation|screenSize"
android:theme="#style/LaunchScreenTheme"
android:launchMode="singleTask">
<meta-data android:name="SET_THEME_ON_LAUNCH" android:resource="#style/AppTheme" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="veganbeacon" />
</intent-filter>
</activity>
<activity android:name="com.tns.ErrorReportActivity"/>
</application>
</manifest>
Looking through logcat in Android Studio gave me some addition error output:
2019-06-30 07:58:56.785 10645-10645/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mycompany.myapp, PID: 10645
java.lang.RuntimeException: Unable to instantiate application com.mycompany.myapp: java.lang.ClassNotFoundException: Didn't find class "com.mycompany.myapp" on path: DexPathList[[zip file "/data/app/com.mycompany.myapp-rkxokotTtXOg1zrVZvRGdg==/base.apk"],nativeLibraryDirectories=[/data/app/com.mycompany.myapp-rkxokotTtXOg1zrVZvRGdg==/lib/x86, /data/app/com.mycompany.myapp-rkxokotTtXOg1zrVZvRGdg==/base.apk!/lib/x86, /system/lib]]
at android.app.LoadedApk.makeApplication(LoadedApk.java:1069)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5842)
at android.app.ActivityThread.access$1100(ActivityThread.java:199)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1650)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.mycompany.myapp" on path: DexPathList[[zip file "/data/app/com.mycompany.myapp-rkxokotTtXOg1zrVZvRGdg==/base.apk"],nativeLibraryDirectories=[/data/app/com.mycompany.myapp-rkxokotTtXOg1zrVZvRGdg==/lib/x86, /data/app/com.mycompany.myapp-rkxokotTtXOg1zrVZvRGdg==/base.apk!/lib/x86, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at android.app.AppComponentFactory.instantiateApplication(AppComponentFactory.java:50)
at android.support.v4.app.CoreComponentFactory.instantiateApplication(CoreComponentFactory.java:49)
at android.app.Instrumentation.newApplication(Instrumentation.java:1120)
at android.app.LoadedApk.makeApplication(LoadedApk.java:1061)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5842) 
at android.app.ActivityThread.access$1100(ActivityThread.java:199) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1650) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:6669) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
I think you had modified
<application
android:name="com.tns.NativeScriptApplication"
to
<application
android:name="com.mycompany.myapp"
You may do it only if you are extending your own custom application class.

Android app not permitting cleartext traffic inspite of adding xml permissions

I'm trying to access a development server API using nativescript-vue. I have added all the possible permissions in the android manifest, but it's giving the error: JS: Error: java.io.IOException: Cleartext HTTP traffic to url not permitted
Here is my manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:usesCleartextTraffic="true"
android:name="com.tns.NativeScriptApplication"
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:cleartextTrafficPermitted="true"
android:usesCleartextTraffic="true"
android:networkSecurityConfig="#xml/network_security_config"
android:theme="#style/AppTheme">
Here is the network_security_config.xml file:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">192.168.xxx.xxx</domain>
</domain-config>
</network-security-config>
And here is the Nativescipt-vue code:
httpModule.request({
url: "http://192.168.XXX.XXX:XXXX/func",
method: "POST",
headers: { "Content-Type": "application/json" },
content: data
}).then((response) => {
const result = response.content.toJSON();
}, (e) => {
console.error(e);
});
For those who face the same issue, tns platform remove android and tns platform add android worked for me. It started reading the updated manifest after this.
Go in to App_Resources -> Android -> src\main -> AndroidManifest.xml add android:usesCleartextTraffic="true" go to the application xml section then do a tns update resources cmd.

Nativescript : local notification, builder.setChannelId is not a function error

In my nativescript appllication, I use nativescript-local-notifications NPM to push the local notification and I have followed the instructions same as the readme file in the github.
I face the error
LocalNotifications.schedule: TypeError: builder.setChannelId is not a function
I referred the GitHub issue which is already resolved by someone. But still, I face the issue.
ItemComponent.ts:
import * as LocalNotifications from "nativescript-local-notifications";
scheduleTesting() {
console.log("I am inside schedule noti");
LocalNotifications.hasPermission().then(
function (granted) {
console.log("Permission granted -->" + granted);
}
)
LocalNotifications.schedule([{
id: 0,
title: 'Sound & Badge',
body: 'Who needs a push service anyway?',
badge: 1,
at: new Date(new Date().getTime() + (5 * 1000)) // 5 seconds from now
}])
LocalNotifications.addOnMessageReceivedCallback(data => {
alert({
title: "Local Notification received",
message: `id: '${data.id}', title: '${data.title}'.`,
okButtonText: "Roger that"
});
});
}
manifestoXML
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="__PACKAGE__"
android:versionCode="1"
android:versionName="1.0">
<supports-screens
android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:xlargeScreens="true"/>
<uses-sdk
android:minSdkVersion="17"
android:targetSdkVersion="__APILEVEL__"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:name="com.tns.NativeScriptApplication"
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name="com.tns.NativeScriptActivity"
android:label="#string/title_activity_kimera"
android:configChanges="keyboardHidden|orientation|screenSize"
android:theme="#style/LaunchScreenTheme"
android:launchMode="singleTop"
>
<meta-data android:name="SET_THEME_ON_LAUNCH" android:resource="#style/AppTheme" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="android.app.shortcuts"
android:resource="#xml/shortcuts" />
</activity>
<activity
android:name="com.tns.ErrorReportActivity"/>
</application>
</manifest>
API level = 27
"nativescript-local-notifications": "^2.0.3",
GITHub issue url : https://github.com/EddyVerbruggen/nativescript-local-notifications/pull/68

Ajax call with cordova whitelist error

I've seen many posts about implementing cordova whitelist plugin but after a full week of testing i still haven't spotted what's my mistake.
This ajax call throws these alerts:
xhr {"readystate":0,"status":0,"statustext":"error"}.
status "error"
error ""
$.ajax({
url: 'http://www.example.com/my_file.php',
data: {type: 'test', code: '11'},
method: "GET",
dataType: "json",
timeout: 5000,
success: function (data) {
alert('done '+JSON.stringify(data));
},
error: function (xhr, status, error) {
alert('xhr '+JSON.stringify(xhr));
alert('status'+JSON.stringify(status));
alert('error '+JSON.stringify(error));
}
});
I updated my phonegap build app with the new cordova whitelist implementation adding this to the meta:
<meta http-equiv="Content-Security-Policy" content="default-src data: gap: https://ssl.gstatic.com 'unsafe-eval' *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval' http://www.example.com; connect-src 'self' http://www.example.com">
this to the config.xml:
<gap:plugin name="cordova-plugin-whitelist" source="npm"/>
<allow-navigation href="*" />
<allow-intent href="*" />
<access origin="*" />
and this in the js before ajax calls:
$.support.cors=true;
I'm using all the wildcards at the moment for the testing, i'll change later. This is the server php file i'm calling:
<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
$data = json_encode(array($_GET));
echo $data;
?>
Phonegap build version cli-5.2.0
Android 4.1.1
any help will be appreciated
Try this in your config.xml
<access origin="*"/>
<access origin="tel:*" launch-external="yes"/>
<allow-navigation href="*"/>
<allow-navigation href="http://*/*"/>
<allow-navigation href="https://*/*"/>
<allow-navigation href="data:*"/>
<allow-intent href="*"/>
<access origin="*"/>

Asp.Net 5 Website Won't Load on IIS Express 10

I am trying to get my ASP.Net 5 MVC6 website to run on IIS Express 10 and it keeps giving me a an error which says:
HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.
(Image Attached for full error)
I have successfully run the website from within Visual Studio 2015 Community but I want an 'Always on' solution so I don't have to keep starting and stopping the website from within VS.
I have the following in the IISExpress/config/applicationhost.config file:
<sites>
<site name="Admin" id="1" serverAutoStart="true">
<application path="/">
<virtualDirectory path="/" physicalPath="C:\Users\Admin\Documents\Visual Studio 2015\Projects\CMS\src\Admin\wwwroot" />
</application>
<bindings>
<binding protocol="http" bindingInformation=":12345:localhost" />
</bindings>
</site>
<siteDefaults>
<logFile logFormat="W3C" directory="%IIS_USER_HOME%\Logs" />
<traceFailedRequestsLogging directory="%IIS_USER_HOME%\TraceLogFiles" enabled="true" maxLogFileSizeKB="1024" />
</siteDefaults>
<applicationDefaults applicationPool="Clr4IntegratedAppPool" />
<virtualDirectoryDefaults allowSubDirConfig="true" />
</sites>
The URL I am using is: http://localhost:12345/
I have the following in my web.config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="httpPlatformHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" />
</handlers>
<httpPlatform processPath="%DNX_PATH%" arguments="%DNX_ARGS%" stdoutLogEnabled="false" startupTimeLimit="3600" forwardWindowsAuthToken="true" />
</system.webServer>
</configuration>
And my project.json file
{
"version": "1.0.0-*",
"compilationOptions": {
"emitEntryPoint": true
},
"dependencies": {
"Microsoft.AspNet.Diagnostics": "1.0.0-rc1-final",
"Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
"Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
"Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
"Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
"Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.FileProviderExtensions" : "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final",
"Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc1-final"
},
"commands": {
"web": "Microsoft.AspNet.Server.Kestrel"
},
"frameworks": {
"dnx451": { },
"dnxcore50": { }
},
"exclude": [
"wwwroot",
"node_modules"
],
"publishExclude": [
"**.user",
"**.vspscc"
],
"scripts": {
"prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ]
}
}
I had the same problem with Azure Web App. I managed to fix it by removing startupTimeLimit and forwardWindowsAuthToken properties from web.config httpPlatform tag. I found the solution by comparing my project to working one. Don't know if removal of properties have some side effects.

Resources