I am developing an app in react native.
I would like to make a call to RapidAPI, such as:
useEffect(() => {
fetch("https://jokes-by-api-ninjas.p.rapidapi.com/v1/jokes", {
method: "GET",
headers: {
'X-RapidAPI-Key': 'myapi',
'X-RapidAPI-Host': 'jokes-by-api-ninjas.p.rapidapi.com'
}
})
.then((response) => response.json())
.then((data) => {
console.log(data);
})
.catch((error) => console.log(error));
}, []);
I am getting this error: [TypeError: Network request failed]
.
I also tried with the axios package and led to the same thing.
I used the python snippet from Rapid API and it worked strait away.
What am I doing wrong ?
EDIT:
I changed NSAllowsArbitraryLoads
to true in my Info.plist, then rebuilt with npx react-native run-ios
, still no luck.
In the following code:
const url = 'https://jokes-by-api-ninjas.p.rapidapi.com/v1/jokes';
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': '79274b9cbamsh648fe97da3e476dp167e86jsnb80a57f2cac5',
'X-RapidAPI-Host': 'jokes-by-api-ninjas.p.rapidapi.com'
}
};
// const url = 'https://jsonplaceholder.typicode.com/posts/1';
// const options = {
// method: 'GET',
// headers: {
// 'Content-Type': 'application/json',
// 'Dummy-Header': 'TestValue' // Custom dummy header for testing
// }
// };
fetch(url, options)
.then(res => res.json())
.then((resJson) => {
console.log(resJson)
resolve()
})
.catch((e) => {
console.log('Error in getAddressFromCoordinates', e)
resolve()
})
First url/option fail and second works. How ?
React Native uses the fetch API, which might behave differently from Python's requests library. Try using the https module in React Native to make the request.
Install
https
module, andThe problem here also could be that iOS does not allow HTTP requests by default, only HTTPS. If you want to enable HTTP requests add this to your info.plist: