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
Related
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
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
I have this route on me BE
app.get('/welcomeRoute',(req,res)=> {
res.send("Hello world")
})
app.listen(4000,()=> {
console.log("Server is up")
})
I installed axios on my react native project with npm i axios , I created my project with expo init.
Here is how I use route
test = () => {
axios.get('http://localhost:4000/welcomeRoute').then((res)=> {
console.log('--------res', res);
}).catch((err)=> {
console.log('--------err', err);
})
}
Whenever i call this route i Always get --------err [Error: Network Error].
I tested this route in the postman and it is working fine.
Any suggestions please?
If the issue is on Android, the solution is to add below in in your AndroidManifest.xml file
android:usesCleartextTraffic="true"
In IOS, unencrypted network requests are blocked by default, i.e. https will work, http will not.
Your server from your emulator/device you need to access server via IP Address. Instead of http://localhost:port you should use http://your_ip_address:port
Actually in React Native you better give ip address of system rather than localhost because the device don't recognize your ip address using localhost
I'm using Dyson to host a little mock server for my React Native app, and trying to fetch from the server. The server appears to be running well and when I visit my desired url, http://localhost:3000/stations, in my browser, I get a nice JSON response.
In my React Native action, though, I get Network request failed:
export function fetchStations() {
return dispatch => {
dispatch({ type: "GET_STATIONS_START" });
fetch("http://localhost:3000/stations")
.then(res => {
return res.json();
})
.then(json => {
dispatch({ type: "GET_STATIONS_SUCCESS", payload: json.stations });
})
.catch(error => {
console.warn(error);
dispatch({ type: "GET_STATIONS_FAILURE", payload: error });
});
};
}
Using a static local URL works, and using, say, the Google Maps API works (even though it's not what I want, it's just a sample API to try).
I would think I may be calling the url wrong but it works in the browser so that seems doubtful. My guess is that is has something to do with iOS not liking http requests (only accepting https), unless you set some setting somewhere (I've been through this in native iOS development).
If this is the problem, how do I fix it from React Native? Or, what is the actual problem?
PS. I'm using dyson rather than json-server because for some reason I can't get json-server to work. See my other post. Somewhere here :)
I figured it out. The device (simulator) doesn't have access to localhost so I had to set my url to http://127.0.0.1:3000/stations and it works like a dream.
Within my react-native app, I get network request failed error on IOS simulator after fetching GET method. I tried on Android and it worked perfectly. I know that for IOS I need to set Allow Arbitrary Loads to "yes" in info.plist in Xcode,but I did it long time ago. Beside, I have lots of other pages(components) that I fetch requests and I do not live any problem on these components. I believe maybe it is something related to URL or response.
Here is my info.plist file
Here is the json that I supposed to get as response of fetch GET method.(BTW, I get the supposed response in ANDROID)
const { dispatch } = this.props;
console.log("Whitespot MAPS Props: ",this.props);
url = '-----------------/coordinates?product=1';
requestOptions = {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + this.props.token
}
};
dispatch(authActions.checkTokenAndFetch(url, requestOptions))
.then((data) => {
console.log("COORDINATES: ",data);
},
(error) => {
console.log("MAP COORDINATES ERROR: ",error);
})
And here is the error I get while running on IOS simulator
I solved the issue. Beside, arbitrary loads, I also need to give permission directly to my server url in info.plist Exception Domains section. So, it works out in this way. Have a good day.
Just like in pic.