OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

React Native Android App Network Request Failed On Physical Device

  • Thread starter Thread starter Keill VunStroke
  • Start date Start date
K

Keill VunStroke

Guest
I am new to react native and currently I am using a bare workflow react native without expo. The scenario is -Have a docker keycloak realm service set up to test some authentication to spit out a token when authenticated

-When running virtual device (virtual phone) using Android Studio, I am able to authenticate and get a token back from docker keycloak service. Also tested with Postman and I am also getting a token.

-When I generate an apk through ./gradlew assembleRelease in the android folder and install it on my device, I always receive error of "Network request failed" -If I plug my phone and use it to debug the app while connected to PC, I still get Network request failed

-So, I am sending a request with HTTP instead of HTTPS and I made sure to go to AndroidManifest.xml and set <application ... android:usesCleartextTraffic="true">

-Before when I was using local 192.168.etc...:8080 It would just network request failed instantly. Now if I use 10.0.2.2, it waits around 7-10 seconds before I get Network request failed

Thank you for anybody's help. I have hit a brick wall here and I am not familiar with networking or connecting.

Here is the code segment for my loginHandler

//-------------------------------------------------------------

Code:
const loginHandler = async () => {
const url = `http://10.0.2.2:8080/realms/testrealm/protocol/openid-connect/token`;
const body = `client_id=login-client&client_secret=SOME+RANDOM+CHARS&username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}&grant_type=password`;

const timeoutPromise = new Promise((_, reject) =>
  setTimeout(() => reject(new Error('Request timed out')), 15000)
);

try {
  setMessage('');
  console.log('Perform login with:', username, password);
  console.log('URL FOR LOGGING:', url);
  console.log('BODY OF URL:', body);

  const fetchPromise = fetch(url, {
    method: 'POST',
    mode: 'cors',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: body,
  });

  const response = await Promise.race([fetchPromise, timeoutPromise]);

  console.log('Response Status:', response.status);

  if (!response.ok) {
    const responseBody = await response.text();
    console.log("LOGIN FAILED", response.status, responseBody);
    setMessage(`Login failed with status ${response.status}: ${responseBody}`);
    setMessageColor('red');
    throw new Error(`Login failed | "LOGIN FAILED", ${response.status}, ${responseBody}, URL: ${url}`);
  }

  const data = await response.json();
  console.log('Login successful!:', data);
  setMessage('Login successful!');
  setMessageColor('green');
} catch (error) {
  console.error('Login error:', error);
  setMessage(`Login error: ${error.message}`);
  setMessageColor('red');
}

};

//----------------------------------------------------------------------------

  • Tried setting in AndroidManifest.xml to set android:usesCleartextTraffic="true"
  • Changing the local ip address to 10.0.2.2 instead of the 192.168.etc... -Using my physical phone device to debug and
<p>I am new to react native and currently I am using a bare workflow react native without expo.
The scenario is
-Have a docker keycloak realm service set up to test some authentication to spit out a token when authenticated</p>
<p>-When running virtual device (virtual phone) using Android Studio, I am able to authenticate and get a token back from docker keycloak service. Also tested with Postman and I am also getting a token.</p>
<p>-When I generate an apk through ./gradlew assembleRelease in the android folder and install it on my device, I always receive error of "Network request failed"
-If I plug my phone and use it to debug the app while connected to PC, I still get Network request failed</p>
<p>-So, I am sending a request with HTTP instead of HTTPS and I made sure to go to AndroidManifest.xml and set
<application
...
android:usesCleartextTraffic="true"></p>
<p>-Before when I was using local 192.168.etc...:8080 It would just network request failed instantly. Now if I use 10.0.2.2, it waits around 7-10 seconds before I get Network request failed</p>
<p>Thank you for anybody's help. I have hit a brick wall here and I am not familiar with networking or connecting.</p>
<p>Here is the code segment for my loginHandler</p>
<p>//-------------------------------------------------------------</p>
<pre><code>const loginHandler = async () => {
const url = `http://10.0.2.2:8080/realms/testrealm/protocol/openid-connect/token`;
const body = `client_id=login-client&client_secret=SOME+RANDOM+CHARS&username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}&grant_type=password`;

const timeoutPromise = new Promise((_, reject) =>
setTimeout(() => reject(new Error('Request timed out')), 15000)
);

try {
setMessage('');
console.log('Perform login with:', username, password);
console.log('URL FOR LOGGING:', url);
console.log('BODY OF URL:', body);

const fetchPromise = fetch(url, {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: body,
});

const response = await Promise.race([fetchPromise, timeoutPromise]);

console.log('Response Status:', response.status);

if (!response.ok) {
const responseBody = await response.text();
console.log("LOGIN FAILED", response.status, responseBody);
setMessage(`Login failed with status ${response.status}: ${responseBody}`);
setMessageColor('red');
throw new Error(`Login failed | "LOGIN FAILED", ${response.status}, ${responseBody}, URL: ${url}`);
}

const data = await response.json();
console.log('Login successful!:', data);
setMessage('Login successful!');
setMessageColor('green');
} catch (error) {
console.error('Login error:', error);
setMessage(`Login error: ${error.message}`);
setMessageColor('red');
}
</code></pre>
<p>};</p>
<p>//----------------------------------------------------------------------------</p>
<ul>
<li>Tried setting in AndroidManifest.xml to set android:usesCleartextTraffic="true"</li>
<li>Changing the local ip address to 10.0.2.2 instead of the 192.168.etc...
-Using my physical phone device to debug and</li>
</ul>
Continue reading...
 

Latest posts

Top