Connecting to local Express API from Expo app using physical IOS device - javascript

I've been trying to work this out for hours. I'm currently trying to learn React Native development with a Node/Express backend. I can't seem to make an Axios get request to my local API from my Expo app running on my IOS device (real device).
I have tried adding
"infoPlist": {
"NSAppTransportSecurity": {
"NSAllowsArbitraryLoads": true,
"NSAllowsLocalNetworking": true,
"NSExceptionDomains": {
"192.168.1.4": {
"NSExceptionAllowsInsecureHTTPLoads": true,
"NSRequiresCertificateTransparency": false
}
}
}
}
to my app.json.
I have also tried the following:
using both localhost and my backends ipv4 address as the requests URL
creating a Self Signed SSL Key for the server, sending the certificate to the iPhone, and trusting it.
pretty much everything you can find on StackOverflow and IOS dev forums.
Here is the axios request that is made from React-Native:
const onLoginPress = () => {
console.log("login pressed");
axios
.post('https://192.168.1.4:5000/api/auth/login', {email, password})
.then(function (response) {
//handle success
console.log(response);
if (response.data.success) alert(`successful login, token: ${response.data.token}`);
})
.catch(function (error) {
//handle error
alert('login was not successful')
console.log(error);
})
};
Here is the error that I get when executing the GET from the iPhone running the app in Expo GO:
Network Error
at node_modules\axios\lib\core\createError.js:16:14 in createError
at node_modules\axios\lib\adapters\xhr.js:117:24 in handleError
at node_modules\event-target-shim\dist\event-target-shim.js:818:20 in EventTarget.prototype.dispatchEvent
at node_modules\react-native\Libraries\Network\XMLHttpRequest.js:609:10 in setReadyState
at node_modules\react-native\Libraries\Network\XMLHttpRequest.js:396:6 in __didCompleteResponse
at node_modules\react-native\Libraries\vendor\emitter\_EventEmitter.js:135:10 in EventEmitter#emit
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:414:4 in __callFunction
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:113:6 in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:365:10 in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112:4 in callFunctionReturnFlushedQueue
Currently, the GET request works when running the Expo app in a web browser and in Postman, if I trust the self-signed certificate of course, or disable SSL verification.
IOS Device where the problem persists is an iPhone 11 Pro Max running IOS 14.8.1

try using ngrok,
download and extract it on the same folder and use this command
ngrok http http://localhost:your_api_port
you will get an ngrok url which you could send requests to from your react native app

Related

Firebase AppCheck web app not working in production mode

I cannot get Firebase AppCheck to work in production mode on a Vue.js project with Firestore and Storage. But It works normally in development.
const appCheck: AppCheck = initializeAppCheck(firebaseApp, {
provider: new ReCaptchaV3Provider(reCaptchaSiteKey),
isTokenAutoRefreshEnabled: true,
});
getToken(appCheck)
.then((result: AppCheckTokenResult) => {
console.log(process.env.NODE_ENV);
console.log(result.token);
})
.catch((e: FirebaseError) => {
console.log(process.env.NODE_ENV);
console.log(e.code + ": " + e.message);
});
In Development mode, using vite, get the token back:
In Production mode, with firebase serve, get appCheck/fecth-status-error:
Firebaser here!
The error you are receiving is due to the App Check backend not being able to verify the underlying reCAPTCHA attestation.
Things to check for:
is reCAPTCHA providing a valid attestation and not somehow thinking your device is a bot?
does the site secret uploaded to App Check for this App match the client ID you are using in the App?
If you are using a Debug Token in your development build, that might explain why that one is succeeding.

How to disable https-only fetch requests in expo react native/node js

Im trying to use fetch API to communicate with my server on the localhost, fetch request throws the following error:
[Unhandled promise rejection: TypeError: Network request failed]
- node_modules\whatwg-fetch\dist\fetch.umd.js:473:29 in xhr.onerror
- node_modules\event-target-shim\dist\event-target-shim.js:818:39 in EventTarget.prototype.dispatchEvent
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:574:29 in setReadyState
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:388:25 in __didCompleteResponse
- node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:190:12 in emit
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:436:47 in __callFunction
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:111:26 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:384:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:110:17 in __guard$argument_0
* [native code]:null in callFunctionReturnFlushedQueue
I have read that ios does only support https requests even though I was able to do this before, the only difference is that I was using xampp/mysql and now im using nodejs with mongoose.
I simply use the following on the front end
fetch("http://localhost:3000/user/login", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
console.log("Success:", data);
console.log("Success");
})
.catch(error => {
console.log(error);
});
The server is working correctly, I can normally post data and login successfully using postman.
(Using JSON)
I have also tried inputting just a random google url (https://google.com) and it returned a readable error which is logical which supported the https concern.
Any suggestions?
Edit:
It appears this has nothing to do with iphones nor ssl, I have installed an android emulator (Pixel XL, R Software), the emulator is not reaching my localhost, I have also tried using my pc's local ip.
I have no idea why its not communicating with the server, is it some expo configuration?
Try using your ip address as the baseUrl: similar to "https://192.XXX.X.XX:3000"
To get it from the terminal run ifconfig and it will be there.
you can setup a self signed certificate on your local web server see: https://shellcreeper.com/how-to-create-valid-ssl-in-localhost-for-xampp/ or you can google other terms similar to "Setup self signed certificate on localhost".

React Native https axios resquest gets Network Error on Android but not iOS

I was building my react native application and using backend URL as http://123.123.123.123:port/ and everything was working fine while in development. but when I built my app and installed it on an android device it wouldn't work and I remember someone telling me that android by default only lets https request. so I changed the URL to the one that the web app is using which is https://example.com/api/... (not self-signed TSL certificate) and now the android can send requests but they all return as Network Errors (when built and when running on an emulator), but it works fine on iOS simulator. I'm new to app development and can't find any solutions online. Maybe there is an option that I'm missing?
My axios setup, that is sending the requests:
const customAxios = axios.create({
baseURL: baseURL,
timeout: 6000,
});
...
const response = await customAxios.post('/login', {
email,
password,
});
Error stack:
Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:81)
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)
The https URL is working on ios and web applications
In your manifest file add android:usesCleartextTraffic="true" inside application tag.
<application
xmlns:tools="http://schemas.android.com/tools"
tools:replace="android:allowBackup"
android:name=".MainApplication"
android:label="#string/app_name"
android:icon="#mipmap/ic_launcher"
android:roundIcon="#mipmap/ic_launcher_round"
android:usesCleartextTraffic="true">...
</application>

Axios request failing on signed version of cordova app

I am developing a Cordova application with Axios and React. I can build this app with Cordova and run the resulting APK on my phone with no problems whatsoever. However, when I sign and zipalign the app and put it on the Play store - network requests do not work.
This is an example of a request :
const instance = axios.create({
baseURL: "http://darajava.ie:8888/api/api",
headers: {
'accept': 'application/json'
}
});
instance.post('authenticate', querystring.stringify({
username,
password,
})).then((res) => {
console.log('LOG ' + JSON.stringify(res));
}).catch(function (error) {
console.log('ERR ' + JSON.stringify(error));
});
The response on the unsigned apk (on the actual phone) is normal, whereas we get "Network Error" from the Play store version. I did some research on Axios' Network Error and it seems that that occurs when it cannot reach the server. Keep in mind that all other requests fail too.
Does anybody know where I would even start to debug this?
The problem was that the newer versions of Android do not support cleartext traffic. Either explicitly allow cleartext or use a secure server.

Ionic Capacitor Network error "at t.exports (http://localhost/js/chunk-vendors.6faaceee.js:7:66512)\n " using Android emulator

I'm using Ionic/Vue and simple axios post request to my server. It works well until I run it on android emulator using capacitor ionic capacitor copy android. But when I tried to login to the android emulator it gives me this error. Please help
2019-07-14 18:48:06.318 9746-9896/io.ionic.starter
I/Capacitor/Plugin/Console: {"message":"Network
Error","name":"Error","stack":"Error: Network Error\n at t.exports
(http://localhost/js/chunk-vendors.6faaceee.js:7:66512)\n at
XMLHttpRequest.l.onerror
(http://localhost/js/chunk-vendors.6faaceee.js:43:11967)","config":{"url":"http://192.168.1.7:3333/api/auth/login","method":"post","data":"{\"username\":\"\",\"password\":\"\"}","headers":{"0":"application/json","Content-Type":"application/json;charset=utf-8","Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"Origin,
X-Requested-With, Content-Type,
Accept"},"proxy":{"host":"http://192.168.1.7","port":"3333"},"baseURL":"http://192.168.1.7:3333/","transformRequest":[null],"transformResponse":[null],"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1}}
It's a CORS error. So you need to use proxy in your Vue app.
// vue.config.js
module.exports = {
devServer: {
proxy: 'http://YOUR_API_URL'
}
}
// AND call 'http://localhost' for api call

Categories

Resources