Network request fails with fetch in Expo React Native - react-native

I am having problems with a simple fetch request in my expo app. Long story short, the user needs to input a prefix and a port. Then we call a fetch request from the address that is made up of these information, expecting a json to verify whether the prefix and the port are correct.
We keep getting the "Network request failed" error. The full error:
Network request failed
at node_modules\whatwg-fetch\dist\fetch.umd.js:null in setTimeout$argument_0
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:null in _allocateCallback$argument_0
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:null in _callTimer
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:null in callTimers
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __callFunction
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in callFunctionReturnFlushedQueue
After several days of trying various solutions we found (specifying Content-Type, multiple cors-related options, some tests and changes on the server from which we are expecting the said json, creating requests with axios or XMLHttpRequest) we ended with this code:
fetch(`https://${prefix}.<the rest of the address>:${port}`, {
method: 'GET',
mode: 'no-cors',
credentials: 'omit',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
})
.then((response) => {
// the address we want to connect to works
...
})
.catch((error) => {
// the prefix or port are incorrect
setError('Incorrect prefix or port');
});
We suspect it might be something to do with ports, since request from here https://dummyjson.com/products/1 works perfectly fine.
Another interesting thig has happened though, that would point more at some caching problems perhaps. Today the request worked for a few minutes on two separate occasions, both were after we changed the Content-Type a few times (one of them was when we set it to "text/xml" and then it worked when we changed to anything, like "application/json", "text/html", even without it). We have cleared the cache, but the same thing happened - we changed the Content-Type a few times and it worked, then it stopped.
We created the project using npx create-expo-app AwesomeProject ("expo": "~45.0.0", "react-native": "0.68.2", from package.json), are running it on Android (physical device) from Win 10. We are also using the Expo Go app while developing our app.
Calling this request in the browser works on both PC and the Android phone.
Thank very much you in advance for your time and any help you could provide

Related

Nuxt 3 $fetch method doesn't work with golang servers?

UPD: you can check this yourself: https://github.com/Rusinas/nuxt-fetch-bug
I know I know this sounds stupid as hell and server language has nothing to do with such problems, but hear me out.
I am trying to load data from my local server using $fetch() (or useFetch, no difference), but I get this error:
FetchError: fetch failed ()
No any other details provided. Server is running using Golang/Fiber. When I am trying to load the same endpoint via Postman, everything is OK:
But when I try to load the SAME endpoint in my nuxt 3 application:
I get this:
But my golang server logging this as success:
The more weird thing about all this is that if I run my nodejs version of the exact same server (or any other random API), I don't get any error.
I am pretty sure that my server working 100% correct, but maybe I lost some header or something, which express put automatically? Here is my response headers:
I also checked nodejs response headers:
Doesn't seem like problem is there.
I have no idea what is happening and I don't know other methods to retrieve async data on server side in nuxt js. I have installed axios, but it throws random errors and works on client side for some reason, which makes using nuxt meaningless. However, axios can call this endpoint and returns my data, but only in browser (despite I call it in setup function without any hooks). I am thinking to switch career now
The problem was that fetch() didn't reconize localhost:9000 for some
reason, but when I changed BASE_URL to 127.0.0.1:9000 it started to
work
I had the same error: FetchError: fetch failed ()
Changing localhost in the url to 127.0.0.1 worked for me.
Writing as a separate answer because some might not find it in the comments.
First I think you are using $fetch in a wrong way, as I've seen Nuxt uses fetch for example:
const data = await fetch(endpoint, {
method: "GET",
mode: "cors"
})
.then(resp => resp.json())
And for the server, just enable CORS header on the response, like this:
// you can replace the asterisk with the clients you want.
c.Append("Access-Control-Allow-Origin", "*")
hope I helped :)

Expo App not retrieving localhost API data on Android Emulator, works in emulator's browser

I am using Expo to create a React Native Application. I am consuming a localhost API run with .Net.
The web version runs fine but when I try and consume the API with my app on an android emulator I get the following error:
Network request failed
at node_modules\whatwg-fetch\dist\fetch.umd.js:535:17 in setTimeout$argument_0
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:123:14 in _callTimer
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:379:16 in callTimers
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
I am using https://10.0.2.2:7203/api/payments and I have tried both the HTTPS and HTTP versions. I can get the response in the emulator's browser after agreeing to the warning that the connection is not secure. I suspect that it has something to do with the SSL certificate but I cannot figure out how to make it work in the application.
Here is the fetch request:
const fetchData = fetch(this.props.api)
.then(res => res.json())
.then(result => this.setState({ items: result }))
.catch(reason => console.log(reason));
Try accessing your backend through emulator's browser first. It could be easier to troubleshoot any issues.
Also try synchronizing your emulator's time to be the same as your host machine time. Time mismatch could cause SSL issues.

Express JS changing line break type to CRLF

I am trying to make a HTTP request from a Flutter App to a Express-JS Server running on an Ubuntu machine. A newer version of Flutter(v1.22.5) throws following error when making the Request:
E/flutter (29477): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: Invalid response, unexpected 10 in reason phrase
The code for making the request looks like this:
final response = await http.get(
'http://XX.XX.XXX.XXX/employees', //Hiding IP address for privacy purposes
headers: {
"Content-Type": "application/json",
"Authorization": api_key,
},
);
print(response.statusCode);
I can confirm by using HTTP-Tester Insomnia that the queried URL does indeed return information.
The issue seems to be known and can be viewed here
According to the Github-Thread, the issue is due to wrong line break format in the headers.
How can I tell Express JS to use CRLF?
For anyone stumbling across this question, I fixed it by reconfiguring my API-Server. Closer inspection of this problem lead to the conclusion that neither the App nor the API was bad, due to the fact no API-Request did actually reach my API-Code. I figured it out by simply looking at the logs. In my case, it was NginX not working properly as a reverse-proxy. I followed this tutorial to properly set it put.

React Native App keeps on returning Network Request failed error with the Fetch method

I have a WAMP server on my localhost, and I'm trying to run the php file inside of it, through my react native app in order to store user information. I know I needed to use my localhost's IPv4, and the port number, then the file location, but I still keep on getting: 'Possible Unhandled Promise Rejection (id: 0): TypeError: Network Request failed', while running my app on an ios device on the expo app.
I've tried making it an https instead of http, but i still keep on getting the same error, I've copy pasted the link into google chrome and it runs the php file, but when i do it on another device on the same network, it takes a very long time to connect but then it times out right away, and yes, my server is online.
fetch('http://[My server's IPv4 address]:80/Fetcher/Users.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: this.state.username,
password: this.state.password,
})
}).then((response) => {response.json()}).then(fullResponse => {
console.warn(fullResponse);
console.warn('out');
}).catch(err => console.error(err));
I expected it to take in the username and password and store them on the table I created on my WAMP server's table under the schema I've created.
What happens instead is I get a Network request failed error on my app
It looks like you are facing the same issue as in this post.
By default Android & iOS are blocking cleartext HTTP resource loading. You'll need to enable it both on iOS and Android as described in the post.
Using https in this case won't work because you do not have a valid server certificate.
Also check the same post for possible other sources of this issue.

React Native Error: Request failed with status code 499

I'm trying to fetch data from an API hosted on Heroku in a React Native app on an IOS simulator, and I keep getting this error Error: Request failed with status code 499 which occurs after a long period of time (close to a minute) from the time the API call is initiated.
The same API calls work well in Android emulator.
Please what could be causing this how can I fix it?
If anybody is still experiencing these issues, make sure that you're not sending a body in your get requests. I had the issue where I sent a GET request with
{
method: 'GET',
url: '<url>',
body: {}
}
because the body was accidentally appended to the request.