Network error with axios and react native - 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'

Related

get CORS problem when ty to get a token in keycloak with vuejs and axios

I trying to access one keycloak with axios in my vuejs app, but I receive the cors error, can someone help me please? (If I make a post from POSTMAN to my keycloak works fine)
I using this code:
const params = new URLSearchParams();
params.append("grant_type", "password");
params.append("client_id", "notas-front");
params.append("username", usuario.value);
params.append("password", password.value);
console.log(params);
const config = {
// withCredentials: true,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
};
axios.defaults.headers.common["Access-Control-Allow-Origin"] =
"http://localhost:8080";
axios
.post(
"http://localhost:8082/auth/realms/lumera/protocol/openid-connect/token",
params,
config
)
.then((response) => {
console.log(response);
});
and get this error:
but when I look the request I can't find the error:
the OPTIONS returns 200
but the POST dont
Postman doesn't care about Same Origin Policy, browser do. That's why your request is working in Postman but not in the browser.
Access-Control-Allow-Origin is a response header, you can't set it on the client request. And as you can see from the OPTIONS response headers your server is returning: Access-Control-Allow-Origin: http://localhost:8080
In a development environment the best way to solve this is setting a proxy in your vue configuration. Otherwise you should configure the server to allow requests from localhost:8080
Configure Web Origins properly in the Keycloak notas-front client config.

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.

Axios has wrong URL only with 'heroku local web'

I've got a problem with axios and heroku. Maybe some short introduction before.
The problem with CORS has been solved and i my apps run on localhost and on herokuapp.com. The only thing which is currently not working is my app running with heroku local web.
For the backend call I using axios which is referencing my backend api from an environment file:
axios
.get(process.env.VUE_APP_ROOT_API + "/resource")
.then(response => (this.receipt = response.data));
}
.env.local:
VUE_APP_ROOT_API=http//:0.0.0.0:5002 #5002 is my backend
This produces the following wrong axios call:
GET http://0.0.0.0:5001/http//:0.0.0.0:5002/resource #5001 is my frontend
I cannot explain how this GET is generated. Printing out the request url with
axios.interceptors.request.use(request => {
console.log("Starting Request", request);
return request;
});
is showing the correct URL http//:0.0.0.0:5002/resource...
Any solutions?
This is embarassing, I had a type:
http:// instead of http//:
See: Quasar Axios request wrong URL (Double URL)

make a HTTP Request from React-Redux from localhost

I am new to React Redux, and All I already did:
1) activate my backend server (localhost:5000)
2) activate my front-end server using npm start (localhost:8080)
3) I tried to dispatch action by using
this.props.dispatch({type: ActionTypes.FILE_UPLOAD_REQUEST, email: this.state.email, file: this.state.policyFile});
4) Using atlas-saga, and call my service function associated with the dispatch :
let result = yield call(Atlas.uploadFile, action.email, action.file);
5) define the function as :
export const uploadFile = (email, file) => {
return fetch(`${BASE_URL}/v1/files/${email}/policies`, {
method: 'POST',
headers:{} ,
body: {'file': file}
})
.then(response => response.json())
}
After I try to run a function at my react( a function that calls the dispatch), it gives me errors that they cannot found the route. This is the error message from the console.
Fetch API cannot load https://api-staging.autoarmour.co/v1/files/fakeemail#gmail.com/policies. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 500. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Yes, I did not create any reducer, just pure function that will upload a file. Thank you
I SOLVE IT, WOHOO!!!
The error message means that its not connected at the backend side at all. You need to make sure that it is connected. I solve it by connecting my redux to my react component. Thanks guys
Cheers!

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.