Can't fetch data from local api React-Native - api

I have a web application, in react using an API made in Laravel. I want to make a mobile app using the same API. I can't fetch data, because I get NETWORK REQUEST FAILED error. This is how I try to fetch data:
handleButton = () => {
try {
fetch(`127.0.0.1:8081/test`).then(response =>
console.log(response)
);
} catch (e) {
console.log(e);
}
};
I tried changing the ip in dev settings to my machine id, i tried using localhost not the ip(127.0.0.1) but none of those fixed it... I can't seem to find anything else. Here is the error text:
Possible Unhandled Promise Rejection (id: 0):
TypeError: Network request failed
TypeError: Network request failed
at XMLHttpRequest.xhr.onerror (blob:http://localhost:8081/cfc373de-8318-4df3-b46a-7b17d4926c5e:42556:18)
at XMLHttpRequest.dispatchEvent (blob:http://localhost:8081/cfc373de-8318-4df3-b46a-7b17d4926c5e:47998:27)
at XMLHttpRequest.setReadyState (blob:http://localhost:8081/cfc373de-8318-4df3-b46a-7b17d4926c5e:46859:20)
at XMLHttpRequest.__didCompleteResponse (blob:http://localhost:8081/cfc373de-8318-4df3-b46a-7b17d4926c5e:46686:16)
at blob:http://localhost:8081/cfc373de-8318-4df3-b46a-7b17d4926c5e:46796:47
at RCTDeviceEventEmitter.emit (blob:http://localhost:8081/cfc373de-8318-4df3-b46a-7b17d4926c5e:16875:37)
at MessageQueue.__callFunction (blob:http://localhost:8081/cfc373de-8318-4df3-b46a-7b17d4926c5e:16488:44)
at blob:http://localhost:8081/cfc373de-8318-4df3-b46a-7b17d4926c5e:16245:17
at MessageQueue.__guard (blob:http://localhost:8081/cfc373de-8318-4df3-b46a-7b17d4926c5e:16442:13)
at MessageQueue.callFunctionReturnFlushedQueue (blob:http://localhost:8081/cfc373de-8318-4df3-b46a-7b17d4926c5e:16244:14)
EDIT:
I am using android studio's emulator, because i don't have an android device running android > 5

Use the IP of your machine on the local network.
Open up terminal/cmd.
If you're using a mac, you can use ifconfig and it's usually under en0. You will see something like 192.168.0.32 or similar.
If you're using windows, you can use ipconfig.

Related

Expo app is throwing when locally hosted api is called

I am using expo in my project and I hosted a local server for API. When I try connecting the API with the expo project it gives me network error:
error Error: Network Error
at createError (F:\Projects\react-native-food-app\node_modules\axios\lib\core\createError.js:16:15)
at XMLHttpRequest.handleError (F:\Projects\react-native-food-app\node_modules\axios\lib\adapters\xhr.js:117:14)
at XMLHttpRequest.dispatchEvent (F:\Projects\react-native-food-app\node_modules\event-target-shim\dist\event-target-shim.js:818:35)
at XMLHttpRequest.setReadyState (F:\Projects\react-native-food-app\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:609:16)
at XMLHttpRequest.__didCompleteResponse (F:\Projects\react-native-food-app\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:396:12)
at F:\Projects\react-native-food-app\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:517:9
at RCTDeviceEventEmitter.emit (F:\Projects\react-native-food-app\node_modules\react-native\Libraries\vendor\emitter\_EventEmitter.js:135:33)
at MessageQueue.__callFunction (F:\Projects\react-native-food-app\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:414:27)
at F:\Projects\react-native-food-app\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:113:12
at MessageQueue.__guard (F:\Projects\react-native-food-app\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:365:9)
This is the code for API calling
const instance = axios.create({
baseURL: "http://127.0.0.1:8000/api/",
});
It works just fine in insomnia but throws an error when I call the API in expo
expo is not support localhost server.
you must use the ip instead of localhost
ipconfig #window
networksetup -getinfo Wi-Fi #mac
and then
const instance = axios.create({
baseURL: "http://192.168.0.100:8000/api/",
});

React Native / Expo : Fetch throws “Network request failed”

I saw several posts on the subject but without result. I have on the one hand a form which collects information (name, first name etc) then saves it in database (mongodb). Everything works when I use postman to send my information via the route / signup, i can see my new user in mongodb. but when i'm starting the app on Expo he throw me "Network request failed".
Frontend fetch :
submitForm = () => {
var signupData = JSON.stringify({
first_name: this.state.firstName,
last_name: this.state.lastName,
email: this.state.email,
password: this.state.password
});
fetch(`https://localhost:3000/signup`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: signupData
})
.then(response => {
console.log(response);
return response.json();
})
.then(data => {
if (data.result) {
this.props.handleUserValid(
this.state.firstName,
this.state.lastName,
this.state.email,
data.user.token
);
this.props.navigation.navigate("Account");
}
})
.catch(error => {
console.error(error);
});
};
And Backend route :
router.post("/signup", function(req, res, next) {
var salt = uid2(32);
console.log("Signup is running...");
const newUser = new userModel({
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email,
password: SHA256(req.body.password + salt).toString(encBase64),
token: uid2(32),
salt: salt
});
newUser.save(function(error, user) {
console.log("LOG: user", user);
res.json({ result: true, user });
});
});
module.exports = router;
And here is a screenshot of the error
Again when using Postman, the fetch is working good, my console log is printed and the user added to my data base.
Thanks for the help.
-- EDIT --
I launched the application in a web browser via Expo and everything works perfectly. My sign in / sign up pages and my account page. But on my phone it's not working (IOS), it's a network problem from my phone (maybe a certificate problem, wrong IP ?)
if you have an idea i'm interested, i've been stuck on it for 2 days
Had the same issue with React-native Expo and Python Django back-end.
The problem is about a conflict between an emulator localhost and server localhost.
Your back-end-server might be ruunning on 127.0.0.1:8000, but an emulator can't find this.
In terminal find your Ipv4-Address with a command 'ipconfig'.
For ex., it will be 192.138.1.40
After this put it into your fetch (
'http://192.138.1.40:8000/').
And what is also important - run your back-end-server with the same host and port.
On python Django for example:
py manage.py runserver 192.138.1.40:8000
On Django you will also need to add ALLOWED_HOSTS = ['192.138.1.40'] in settings.py
Instead of 'localhost', while using expo, use your device's (computer's) IP address (http://192.168.x.x:3000/'signup'). This method worked for me. Make sure that your PC and mobile are connected to the same network. Type ipconfig/all in the command prompt to find IP address.
Update:
Seems like this was my problem coupled with my roommates hogging the wifi bandwidth. Slow internet connection may also be a problem. ATB with your problem.
I had the same issue with Expo: fetch error. For my backend. I use json-server to mock API data. In my case, the json-server runs on http://localhost:3000/playlist
Instead of fetch("http://localhost:3000/playlist"), I did fetch(http://10.0.2.2:3000/playlist), then it worked. Using the Android emulator, it could not find the server's address.
For the reason why using 10.0.2.2, check here. why do we use 10.0.2.2 to connect to local web server instead of using computer ip address in android client
I had the same issue - what worked for me was to:
Run my local server on host 0.0.0.0
Go to network preferences and find my LAN IP address (e.g. 192.168.1.1)
Replace the host in my url in the mobile app with the LAN IP (e.g. http://192.168.1.1:3000/signup)
Reload and test
For anyone using Serverless, I used this command to run on 0.0.0.0
ENV=local serverless offline -s local -o 0.0.0.0
I had a similar issue. Apparently, the emulator does not understand or see 'localhost' as host.
What I did:
run ipconfig on your cmd, copy the ipv4 address, then use that to replace 'localhost' for your server host.
you should check the URL
https://localhost:3000/signup (X)
http://localhost:3000/signup (O)
NOT HTTPS
If anyone facing this issue with a hosted backend server this is for your knowledge.
Used react native expo cli
Backend(Spring Boot) hosted on a Azure server ( Eg URL : https://abcd-spring-app.azurewebsites.net). HTTPS used.
But still I faced the below issue.
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:130:14 in _callTimer
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:383:16 in callTimers
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:416:4 in __callFunction
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:109:6 in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:108:4 in callFunctionReturnFlushedQueue
After some research I found that this is because the slow response time of the server. The network request failed due to the timeout.
So Before testing your app with the backend server, send some requests from the web(or any other way) and up your server. Because some servers get inactive after some time. Make sure you have a good connection.

Network error with axios and react native

I have created an API endpoint using the Django python framework that I host externally. I can access my endpoint from a browser (mydomain.com/endpoint/) and verify that there is no error. The same is true when I run my test django server on locally on my development machine (localhost:8000/endpoint/). When I use my localhost as an endpoint, my json data comes through without issue. When I use my production domain, axios gets caught up with a network error, and there is not much context that it gives... from the debug console I get this:
Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:87)
at XMLHttpRequest.dispatchEvent (event-target.js:172)
at XMLHttpRequest.setReadyState (XMLHttpRequest.js:554)
at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:387)
at XMLHttpRequest.js:493
at RCTDeviceEventEmitter.emit (EventEmitter.js:181)
at MessageQueue.__callFunction (MessageQueue.js:353)
at MessageQueue.js:118
at MessageQueue.__guardSafe (MessageQueue.js:316)
This is my axios call in my react native component:
componentDidMount() {
axios.get('mydomain.com/get/').then(response => { // localhost:8000/get works
this.setState({foo:response.data});
}).catch(error => {
console.log(error);
});
}
If you are trying to call localhost on android simulator created with AVD, replacing localhost with 10.0.2.2 solved the issue for me.
It seems that unencrypted network requests are blocked by default in iOS, i.e. https will work, http will not.
From the docs:
By default, iOS will block any request that's not encrypted using SSL.
If you need to fetch from a cleartext URL (one that begins with http)
you will first need to add an App Transport Security exception.
change from localhost to your ip(192.168.43.49)
add http://
http://192.168.43.49:3000/user/
If you do not find your answer in other posts
In my case, I use Rails for the backend and I tried to make requests to http://localhost:3000 using Axios but every time I got Network Error as a response. Then I found out that I need to make a request to http://10.0.2.2:3000 in the case of the android simulator. For the iOS simulator, it works fine with http://localhost:3000.
Conclusion
use
http://10.0.2.2:3000
instead of
http://localhost:3000
update
might worth trying
adb reverse tcp:3000 tcp:3000
For me, the issue was because my Remote URL was incorrect.
If you have the URL is a .env file, please crosscheck the naming and also ensure
that it's prefixed with REACT_APP_ as react might not be able to find it if named otherwise.
In the .env file Something like REACT_APP_BACKEND_API_URL=https://appurl/api
can be accessed as const { REACT_APP_BACKEND_API_URL } = process.env;
Try
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json"
If you are using android then open your command prompt and type ipconfig. Then get your ip address and replce it with localhost.
In my case, first I used http://localhost:8080/api/admin/1. Then I changed it to http://192.168.1.10:8080/api/admin/1. It worked for me.
Make sure to change localhost to your_ip_address which you can find by typing ipconfig in Command Prompt
Trying adding to your AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I was facing the same issue.
i looked deeper and my
endpoint url was not correct.
By giving axios right exact url, my api worked like charm.
Hope it may help anyone
Above mentioned answers only works if you are using localhost but if your code is hosted on a server and Axios throwing Network Error then you can solve this by adding one line.
const config = {
method: 'post',
url: `${BASE_URL}/login`,
headers: {
'Content-Type': 'multipart/form-data'. <----- Add this line in your axios header
},
data : formData
};
axios(config).then((res)=> console.log(res))
I'm using apisauce dependancy & Adding header work for me with React Native Android.
Attach header with request like below:
import { create } from 'apisauce';
const api = create({
baseURL: {baseUrl},
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
});
export async function empLogin(data) {
try {
const response = api.post('Login', data);
return await response;
} catch (error) {
console.log(error);
return [];
}
}
before:
axios.get("http://localhost:3456/apt")
.then(
response => {
alert(JSON.stringify(response));
....
}
)
.catch(function(error) {
alert(error.message);
console.warn(error.response._response);
});
I get Error "Network error" Failed to connect to the localhost after that, I make some steps to resolved the error.
Network Error related to axios resloved by the disabling the system firewall and access from the system IP Address like
axios.get("http://192.168.12.10:3456/apt")
.then(
response => {
alert(JSON.stringify(response));
....
}
)
.catch(function(error) {
alert(error.message);
console.warn(error.response._response);
});
For me adding "Accept" in headers resolved the problem:
Accept: 'application/json'

electron certificates network

I am trying to write a simple electron app to interface with a REST server. The server doesn't have the appropriate certificates. When I try to make a 'GET' request (using fetch()), I get the following error message:
Failed to load resource: net::ERR_BAD_SSL_CLIENT_AUTH_CERT
Fixing the certs is not currently an option. I tried to use the 'ignore-certificates-error' flag (see below). It seems like it should allow me to skip over this error, but it doesn't.
var electron = require('electron');
var app = electron.app
app.commandLine.appendSwitch('ignore-certificate-errors');
...
The result is the same error.
Questions:
I am correct in assuming this options is supposed to help here?
If so, any ideas what I am doing wrong?
Electron version: 1.2.8
Thanks!
You can update your version of electron and use this callback:
app.on('certificate-error', (event, webContents, link, error, certificate, callback) => {
if ('yourURL/api/'.indexOf(link) !== -1) {
// Verification logic.
event.preventDefault();
callback(true);
} else {
callback(false);
}
});
That you going do the fetch to your api with https.

Cannot connect to MobileFirst Server during initialization

I am testing developing a Hybrid application in MobileFirst Studio and want to connect to MobileFirst Server during the app init. I updated main.js file under MF_Project/app/[appNanme]/common/js/main.js init method with the following:
WL.Client.connect({
onSuccess: function() {
WL.Logger.info("onSuccess: connection success");
},
onFailure: function(err) {
WL.Logger.info("onFailure: Exception: " + err);
}
});
I then build the app for Android environment (right click the appName the one under MF_Project and select "Build for Android environment"). Then I ran the app as Android Application in emulator, but the log comes back with error
01-25 16:04:29.364: E/NONE(2755): Invalid invocation of method WL.Client.connect; Invalid value 'undefined' (undefined), expected type 'function'.
01-25 16:04:29.368: E/NONE(2755): Invalid invocation of method WL.Client.connect; Invalid options attribute 'onSuccess'. Invalid invocation of method WL.Client.connect; Invalid value 'undefined' (undefined), expected type 'function'.
Any insight on this would be appreciated.
I have tested the supplied project in MFP 6.3 using a Nexus 5 device running Android 5.0.1.
The application successfully connected to the MFP Server.
In the log I saw the SUCCESSFUL: [object object] message.
[object object] because you did not JSON.stringify the result.
For example: WL.Logger.info("SUCCESSFUL: " + JSON.stringify(response));
I think something is wrong with your generated AVD - try to create a new one, in addition to testing in an actual device.