Supposely I have the same post request on Postman and in a React Native code the Postman request executes successfully but the axios post request fails. On the console I just get "axios network error".
axios
.post("http://localhost:3000/passageiros",
{
nome: "Diego",
celular: "898",
senha: "23232323",
}
)
.then((response) => {
setPost(response.data);
});
I've tried several approaches to check the error but just the generic erro "axios network error" shows.
Related
I am using axios in react native project but at the time of post request through axios it gives an error
export const login = (email, password) => async dispatch => {
const config = {
headers: {
'Content-Type': 'application/json'
}
};
const body = JSON.stringify({ email, password });
console.log(body)
const res = await axios.post(`http://localhost:8000/auth/jwt/create/`, body, config);
console.log('kk');
dispatch({
type: LOGIN_SUCCESS,
payload: res.data
});
dispatch(load_user());
};
On postman this axios request is executing successfully and on the same backend address my react JS project is working correctly and this axios request also get successful.
On react native project it gives following error.
I've also tried try and catch blocks but after execting axios.post line it goes to catch block .
I've tried the same request on Postman and it's successfully sent the post request and get the tokens
Solution 1
Check this. Maybe you should set android:usesCleartextTraffic="true" in your AndroidManifest.xml file.
Solution 2
I could suggest the next command which I personally always use when developing RN apps on Android using local emulators. adb reverse tcp:8081 tcp:8081.
Solution 3
Use concrete local ip-address instead of localhost alias. Check this.
When I use fetch() method to make get request, it failed with "TypeError: Network request failed". It's weird that it sometimes failed but sometimes succeeded. I have tried the solution here: React Native fetch() Network Request Failed, but it didn't work for me. By the way, I am using Android.
This is my code :
try {
let url = "http://140.116.245.229:3000/GetCarsJson";
let data = await fetch(url);
let toJson = await data.json();
} catch(err) {
throw err;
}
This is the error message :
enter image description here
You should ensure your devices/simulator/emulator can connect to this endpoint
If you use Android emulator, you can refer this link How to connect to a local server from an android emulator?
I'm new to react-native, I want to fetch some data from my local laravel server, but I fire the mobx action I get the following errors:
Network Error
[Unhandled promise rejection: Error: Network Error]
This is my mobx action (I'm using flow, similar to async/await), I get 'fire' log but after that I get the error above:
listProducts = flow( function*(payload)
{
console.log('fire');
try
{
let response = yield axios.get('http://192.168.1.39:8000/api/products', { params: payload });
this.posts = response.data;
this.pagination = response.data.pagination;
console.log(response);
//return response;
}
catch (error)
{
console.error(error);
throw error;
}
});
As you can see I'm using my local IP instead of localhost, I'm also testing my app on my android device using EXPO connected to the same network as my dev laptop.
Ciao, I can't see errors on your code. Try to follow this guide to handle Unhandled promise rejection. Could help you to find a clue.
In brief the guide suggest to use axios interceptors:
axios.interceptors.response.use(
response => response,
error => {}
)
I created service in Visual Studio with Conveyor extension to make it accessible in local network. I installed certificate on my Android device so there is green padlock when calling it in browser and service works fine.
However when calling it from React Native app with axios then i get Network error.
That's my code:
const fetchData = async () => {
console.log('url', `${Settings.API_URL}/location/GetDataByMyIp`);
try {
const result = await axios(
`${Settings.API_URL}/location/GetDataByMyIp`,
);
console.log('result', result);
ipData = {
city: result.data.city,
longitude: result.data.longitude,
latitude: result.data.latitude,
};
} catch (e) {
console.log('error', e);
}
};
await fetchData();
In console i see:
url https://192.168.1.14:45455/api/location/GetDataByMyIp
error Error: Network Error
at createError (path_to_app\node_modules\axios\lib\core\createError.js:16)
at EventTarget.handleError (path_to_app\node_modules\axios\lib\adapters\xhr.js:83)
at EventTarget.dispatchEvent (path_to_app\node_modules\event-target-shim\dist\event-target-shim.js:818)
at EventTarget.setReadyState (path_to_app\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:575)
at EventTarget.__didCompleteResponse (path_to_app\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:389)
at path_to_app\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:502
at RCTDeviceEventEmitter.emit (path_to_app\node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:189)
at MessageQueue.__callFunction (path_to_app\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:425)
at path_to_app\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112
at MessageQueue.__guard (path_to_app\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:373)
I tried to add this line to AndroidManifest.xml application tag but still have the error
android:usesCleartextTraffic="true"
Some solutions say about adding as 2nd parameter to axios, but it doesn't work with React Native.
new https.Agent({
rejectUnauthorized: false,
});
I tried to call some other service from the internet and then error was gone.
Is there some solution to this? I haven't found anything more. My last idea is to host service on Azure so I'll have properly signed SSL, but i guess it has to be a way to run it locally.
Edit: It works through http
I am trying to upload some data using axios post request and custom headers. Here is my code.
axios
.post('https://website.domain/api/ads/create', new FormData(), {
headers: {
Authorization: 'Bearer 123',
},
})
.then(res => {
this.setState({ message: JSON.stringify(res) });
})
.catch(res => {
this.setState({ message: JSON.stringify(res.response) });
});
this works fine with Expo (here is the source)
But when move to react native it does not work. It gives me the error:
{message:"Network error".....}
PS: other methods like post without authorization, get all are working except this one.
I found the solution! The trick was with uploading the file: with expo you need to remove //file prefix of file path while in react-native it should be preserved!