Why in React Native post request can't be sent? - react-native

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.

Related

Post not working on axios with React Native

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.

How to make a fetch request to localhost in React Native/Expo?

I'm creating a React Native/Expo app that uses Deno on the backend. I've created an API in the backend that I can run locally on localhost:4000. When I try to use fetch to call the API in the Expo app, however, I keep getting an error
[Unhandled promise rejection: TypeError: Network request failed] at node_modules/whatwg-fetch/dist/fetch.umd.js:535:17 in setTimeout$argument_0
Here is how I set up the backend
import { Application } from "https://deno.land/x/oak/mod.ts";
import { oakCors } from "https://deno.land/x/cors/mod.ts";
import { APP_HOST, APP_PORT } from "./config.ts";
import router from "./routes.ts";
import _404 from "./controllers/404.ts";
import errorHandler from "./controllers/errorHandler.ts";
const app = new Application();
app.use(oakCors());
app.use(errorHandler);
app.use(router.routes());
app.use(router.allowedMethods());
app.use(_404);
console.log(`Listening on port:${APP_PORT}...`);
And how I use fetch to call the API
const App = () => {
const getData = async () => {
const response = await fetch("http://localhost:4000/something");
const data = await response.json();
console.log(data);
};
useEffect(() => {
getData();
}, []);
return (
...
);
};
Note
Some answers on StackOverflow suggest fetching http://[IP_ADDRESS]:4000/something instead of localhost. I've tried that with no luck.
I've verified that the API is working. I can call it successfully in VSCode's Thunder Client and I can also see the data by going to http://localhost:4000 in the browser.
I found a solution to this issue. I'm running my Expo app on a physical device while my server is running on my computer, on localhost. It makes sense that I'm unable to make requests to localhost on my device, because localhost is not running there.
I fixed this issue by using ngrok, a tool that forwards localhost to a cloud URL, and fetching that URL in the app.
Use the local IP assign to your device, like: http://192.168.20.109:port/api/x
find the local IP using the command "ipconfig" in windows or ifconfig in linux

HTTP requests does not work on my real android device (React Native Expo Tunnel)

I'm facing this issue while posting data to my server via axios.post(). It always catches the error "Network Error" when I run my app on my real android device. But when I use an android emulator device, it works correctly and returns the response. I tried to use "ngrok http 5000" and used the uri that ngrok gave me but that didn't work either. I'm hopeless at this point because my app is using QR code scanner and indie notifications. I'm unable to test it while using emulator. Please help me!
I'm leaving my axios.post() method below
const login = async (email, password, navigation) => {
userState.loading = true;
axios
.post(`http://${localIP}:5000/api/user/login`, {
email,
password,
})
.then((response) => {
userState.loading = false;
userState.user = response.data;
console.log("Data: ", response.data);
navigation.reset({
index: 0,
routes: [{ name: "Home" }],
});
})
.catch((err) => {
userState.loading = false;
console.log("ERR :", err.message);
});
};
I tried to use "ngrok http 5000" and used the uri that ngrok given me but that didn't work either.
Might be a little light on information in order to give a definite answer, it's worth looking at installing a debugger and inspecting the network requests to see where they're going wrong. But here's a couple things to try:
In your AndroidManifest.xml file add the line: <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Use http://my.local.ip:port instead of http://localhost:5000 (looks like you're doing this anyway, if not you get this via ipconfig in Command Prompt)
Try adding "Content-Type": "application/json", Accept: "application/json" headers to your Axios request

React Native not allowing public route call to local strapi server

fairly new with strapi and react native. I created a strapi server and created a route that is public, with public authorization to find and find one(Which i'm guessing is the necessary ones to be public) that works perfectly fine if I call it on postman, even if I type it in the browser, and does not require any authorization or header, but when calling it from my react native app on android simulator it gives me a 401 error, which is strange because I can't find any other way I could possible make it more public, but I'm guessing I'm missing something has anyone had this problem?
Another thing that is strange is when running my react native in web it works fine... it's just on the android simulator
This is my call on my react native!
useEffect(() => {
const fetchAllUpdates = async () => {
await axios
.get(`http://localhost:1337/api/updates`, {
headers: {
'Content-Type': 'application/json',
},
})
.then((res) => {
console.log('Data From Strapi ===>', res);
dispatch(setUpdates(res.data.data));
})
.catch((error) => console.log(`Strapi Error===> ${error}`));
};
fetchAllUpdates();
}, []);
Thank you in advance!
Ok I have figured it, the issue is that the android simulator does not have access to the local server the same way as the browser... so instead of calling
http://localhost:1337/api/updates
One has to find the machine ip address, and we can do that by typing
ipConfig
into the terminal and you will get your ip address then replace the
localhost
with the ip and it works
You should have something like this at the end
http://192.168.7.469:1337/api/updates

React native 'Network error' with post Custom header and form data

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!