I have a react-native app that logs in and grabs user information based on the following code:
TestCall(){
console.log(`${myLocation}/login`);
return fetch(`${myLocation}/login`, {
method:'POST',
headers: {Accept: 'application/json',
'Content-Type': 'application/json',
},
credentials: "include",
body: JSON.stringify({
email:this.state.email,
password:this.state.password,
})
})
.then(response => response.json())
.then(json => console.log(json))
}
I have different options for myLocation because I'm using this to grab account info from multiple sites that all allow login based on email and password. All start with https. This works perfectly for IOS no matter what I'm using for myLocation. This works perfectly on Android for all except for one option for myLocation.
For this specific combination of this specific myLocation and Android I get 'Network Request Failed' no matter which user account I try. This includes user account/myLocation combos that work on IOS. It's not giving me a 400, or 404, or 500 or anything like that because it's not even getting that far. When I use catch to see what's happening it just goes straight to the catch and always gives me the 'Network Request Failed' as the error that's being logged.
Also, I am using Android emulator and IOS simulator on the same computer so IP gateway and IP address are the same for both. Only user agent is different (okhttp for android and CFNetwork Darwin for IOS). I'm stumped. Does anyone know why this would be happening? Thanks!
This problem went away after the certificate was changed for the site that I was having a problem with.
Related
I'm using this code to send a verification email with a custom dynamicLinkDomain links.myapp.com.
final acs = ActionCodeSettings(
url: 'https://myapp.com/finishLogin',
handleCodeInApp: true,
iOSBundleId: 'com.myapp.mobileApp',
androidPackageName: 'com.myapp.mobileApp',
androidInstallApp: true,
androidMinimumVersion: '18',
dynamicLinkDomain: 'links.myapp.com',
);
await SecureStorageService.to.postEmail(email);
await FirebaseService.to.auth.sendSignInLinkToEmail(
email: email,
actionCodeSettings: acs,
);
That dynamicLinkDomain is setup correctly because I am using it in my app both with Android and iOS. But when I click on the login link on an Android device (emulator or real) I always get a 400 API key expired error
I tried
to clean the project with flutter clean
create a new API key without restriction
but I still get the error. It seems like a dynamic link problem, but I can't spot it. Does someone have an idea?
I can see that i have in the email is very different depending if I'm generating the email from iOS
https://links.myapp.com/?link=https://links.myapp..com/__/auth/action?apiKey%3DAIzaS...NedNY%26mode%3DsignIn%26oobCode%3DKI4NK...F4ao-7yw%26continueUrl%3Dhttps://myapp..com/finishLogin%26lang%3Den&ibi=com.myapp..mobileApp&ifl=https://links.myapp..com/__/auth/action?apiKey%3DAIza...tNedNY%26mode%3DsignIn%26oobCode%3DKI...-7yw%26continueUrl%3Dhttps://myapp..com/finishLogin%26lang%3Den
or Android
https://links.myapp.com/__/auth/action?apiKey=AIza...edNY&mode=signIn&oobCode=XQI...2pCw&continueUrl=https://myapp.com/finishLogin&lang=en
Is that normal?
I get "Http failure response for https://www.google.com: 0 Unknown Error" when I request from Secured url.
I am trying to test my ionic/angular mobile app. When I tried with http requests I had problem with Android 9, but with Android 7 was working fine. Anyhow I need to set my backend to public https server. So now I'm testing with https request and none of 7 and 9 Android versions works.
I am using Angular 7 ,
"#ionic/angular": "^4.6.1",
"#ionic-native/core": "^5.0.0",
"rxjs": "~6.5.1"
I made these small functions in order to make my problem simpler.
inside my html file i have this code:
myFile.html
<ion-button
(click)="onStartTest()"
>Click me</ion-button>
<p id="testme"></p>
myFile.page.ts
onStartTest() {
this.taskService.onTest().subscribe(result => {
document.getElementById('testme').innerText = 'result ' + result;
console.log(result);
}, error => {
document.getElementById('testme').innerText = error.message;
console.log('Problem ', error.message);
});
}
myTask.service.ts
onTest() {
return this.http.get('https://www.google.com').pipe(
catchError(err => {
return throwError(err);
})
);
}
At first I tried my server's URL but I changed it to "https://www.google.com" just to verify that the backend is correct.
Also I have an interceptors.ts file that I am using it for authentication, but I am not logged in when I execute the onStartTest() function, but im gonna share it anw.
interceptors.ts
import {Injectable} from '#angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '#angular/common/http';
import {Observable} from 'rxjs';
#Injectable()
export class TokenInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = localStorage.getItem('auth_token');
let newHeaders = req.headers;
if (token) {
console.log(token);
newHeaders = newHeaders.set('Authorization', 'Token ' + token);
const modified = req.clone({
headers: newHeaders
});
return next.handle(modified);
} else {
newHeaders = newHeaders.set('Content-Type', 'application/json');
const modified = req.clone({
headers: newHeaders
});
return next.handle(modified);
}
}
}
I think these are the necessary files to share for this problem.
I also tested the url of google with Postman just to be sure that I should get a status 200
I am also aware that there is an "add_header" directive (nginx) that adds 'Allow-access-control-origin' when the response code is 20x or 30x. According to my screenshot with Postman, google is responding with 200 status, but my app still gets status 0 error.
Ignore the first Error. It's a function I use with http when the app begins. Right now im testing https.
I tried superficially to use ionic-native library HTTP but my app totally crashed.
I also execute the command ionic serve --ssl but still nothing.
I read somewhere that for secured connection I need a certificate, but I understood that this is a server's work.
I tried to request from Dark Sky from Vanilla JavaScript and it works fine. So there is something wrong with angular/ionic side and not server's.
What am I missing? I really need to fix this problem soon!
I want to send a secured request to an https url and get the appropriate response.
Your main problem is that you are trying make an API to an unsecure call (http) location (http://192....../mobile/tasks) from a secure origin (https://localhost:8100).
This is clearly indicated in your error message and this is not allowed, and has been answered before
Your second problem is that, for testing purposes, you are trying to call a 3rd party https ressource from your website. This only works if the 3rd party ressource implement CORS, which is not the case for Google and api.darksky.net. Sending a GET request with Postman is useless, as Postman will not check for CORS headers before displaying the response. If you want to use Postman to check CORS, send an OPTIONS request to these ressources and you'll see that there are no CORS headers
So the answer is in MDN - CORS
For security reasons, browsers restrict cross-origin HTTP requests
initiated from scripts. For example, XMLHttpRequest and the Fetch API
follow the same-origin policy. This means that a web application using
those APIs can only request resources from the same origin the
application was loaded from, unless the response from other origins
includes the right CORS headers.
This means the back-end I was using needed some more configuration since I was using 'same-origin' policy script. I thought we had it because when we tried from the browser's console to fetch the request it was working fine, but on mobile it wasn't. We had a custom CORS configuration but we changed it to the django-cors-headers. Since we switched to django-cors-headers I could get correctly the response from HTTP and HTTPs requests.
The other answer and comments were really useful to focus to the right direction.
My company has built a medium size Ionic application and now we're trying to make available natively for Android and iOS and I'm having an issue with persisting cookies.
When running the application Safari there are no issues at all, cookies persist just fine, but when building for devices, the cookies are not being persisted.
The way things work now is when a user logs in, a cookie is returned from the server. After this, the cookie should be sent with every subsequent request, ensuring that the user is still logged in. When I look at the initial response from the server after login, the 'set-cookie' header is there. However, all requests afterward don't contain the cookie, so the server returns a response of not logged in. This only happens when running natively on iOS or Android.
When I debug to see if the cookies are being persisted, I see that there are no cookies.
I know there was a similar issue with iOS 13, but I'm not using iOS 13, I'm using iOS 12. And my problem is on both Android and iOS. When doing Google searches, all the workarounds I see are for problems that are not the same as the one I'm having, and I've tried those workarounds anyways, and they don't work.
Has anyone experienced this issue before? Any ideas on what this might be and how to fix it would be greatly appreciated, I haven't gotten anywhere and I've been searching for an answer for days now.
Also too, because the cookie is HttpOnly I'm not able to access using TypeScript, so I can't persist the cookie manually without sending a non-HttpOnly cookie. Which isn't really an option at the moment.
i had some troubles with cookies and cordova too .
In my case, the plugin cordova-plugin-cartegraph-cookie-master helped me to get and set cookies.
Source Plugin:
https://www.npmjs.com/package/cordova-plugin-cartegraph-cookie-master
Install :
cordova plugin add cordova-plugin-cartegraph-cookie-master
Usage :
Get cookie value :
cookieMaster.getCookieValue('http://<some host>:<some port>', '<cookie name>', function(data) {
console.log(data.cookieValue);
}, function(error) {
if (error) {
console.log('error: ' + error);
}
});
Set cookie value :
cookieMaster.setCookieValue('http://<some host>:<some port>', '<cookie name>', '<cookie value>',
function() {
console.log('A cookie has been set');
},
function(error) {
console.log('Error setting cookie: '+error);
});
I'm trying to receive some simple json from mocky.
React native fetch function:
getMemberDomainList = async (name) => {
try {
let response = await fetch('https://5c9cc9ed3be4e30014a7d287.mockapi.io/api/domain', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
});
let responseJson = await response.json();
return responseJson;
} catch (error) {
console.error(error);
}
}
I have tested the address in chrome on windows, it returns the expected mock data. But when the function is called on my android phone I get this error
Error from remote debugger
...\node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:2348 TypeError: Network request failed
at XMLHttpRequest.xhr.onerror (...\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:4337)
at XMLHttpRequest.dispatchEvent (...\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:10760)
at XMLHttpRequest.setReadyState (...\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:10511)
at XMLHttpRequest.__didCompleteResponse (...\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:10343)
at ...\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:10449
at RCTDeviceEventEmitter.emit (...\Libraries\Components\DrawerAndroid\DrawerLayoutAndroid.android.js:11)
at MessageQueue.__callFunction (...\Libraries\ART\ReactNativeART.js:362)
at blob:http://localhost:8081/79251787-d190-4650-8040-23d091c08738:2334
at MessageQueue.__guard (...\Libraries\ART\ReactNativeART.js:312)
at MessageQueue.callFunctionReturnFlushedQueue (...\Libraries\ART\ReactNativeART.js:139)
I'm also running a WebView in my app, which is pointing to a web url, it loads perfectly so I am sure that the phone has internet permission and access etc.
In the latest android versions http requests are not allowed by default. Take a look at this post for further information about allowing http request: How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?
Can't get mockapi.io to work. But the error is not persistent when using services such as:
https://jsonplaceholder.typicode.com/todos/1
Might not be an android or react native related problem after all. Also had issues with mockapi.io in postman, though it works fine in chrome.
If you are using emulator then check whether internet is working or not in this emulation using browser. If not check this: Android emulator not able to access the internet
I have also face this problem in emulator but when I generate a release app and install in a real device(andoid 9) then it works fine.
Please check backend response status.
If backend is sending contents using 205 status - 205 RESET CONTENT
Android system recognize it as an error - HTTP 205 had non-zero Content-Length: 25.
You can check the status code on postman.
So, in this case, the error should be fixed on backend.
It should send contents with 200 status code.
I was just working around with react native for implementing phone verification for android and ios version but when i tried the example version i couldn't get it working because it gives me a error: Oops! Network request failed.
I got no idea why is this so or have i missed any cruciel step and i couldn't possibly find any tutorial or enough support for that program anywhre so please tell me if iam missing anything.
Here is a screenshot of the error iam getting: https://preview.ibb.co/krbyFk/screenss_PM.png
This is the program i been trying to work around: https://github.com/joinspontaneous/react-native-phone-verification
Edited, I see in the code that
const api = new Frisbee({
baseURI: 'http://localhost:3000',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});
Do i have to do something specifically about that?
I was getting the same error because I was running this on emulator. when running on real device this error went . Also ensure that you have any dummy server running on the specified port.