Error fetch network request failed with react-native - react-native

I am a beginner with fetch and trying to get some data from JSON-server to my react native app but it gave me the same error always... "network request failed"
I tried to use Ip instead of localhost like "http://192.168.x.x:3000" but nothing changed and my expo is 192.168.x.x:19000. what I forgot to do? and why this error always happened?
export const fetchDishes = () => (dispatch) => {
dispatch(dishesLoading());
return fetch("http://192.168.1.5:3000/dishes")
.then(
(response) => {
if (response.ok) {
return response;
} else {
var error = new Error(
"Error " + response.status + ": " + response.statusText
);
error.respone = response;
throw error;
}
},
(error) => {
var errmss = new Error(error.message);
throw errmss;
}
)
.then((respone) => respone.json())
.then((dishes) => dispatch(addDishes(dishes)))
.catch((error) => dispatch(dishesFailed(error.message)));
};
My Expo screen

Related

Vue PWA Workbox (InjectManifest) type error Failed to fetch

I've a Pwa Vue.js APP and I'm using #vue/cli-plugin-pwa plugin. I've setup a fetch event listener in my service-worker.js file, and When I get offline and reload the page its not getting serve from offline and show the error in console
service-worker.js:33 Uncaught (in promise) TypeError: Failed to fetch
at service-worker.js:33:27
Here is my service-worker.js file
importScripts("/precache-manifest.b0639782b7bbcefc0a5a16737bab59a4.js", "https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js");
const bgSyncQueue = new workbox.backgroundSync.Queue('uploadQueue', {
maxRetentionTime: 60 * 24 * 60,
onSync: () => syncData(),
});
workbox.routing.registerNavigationRoute('/index.html');
this.onfetch = (event) => {
let requestClone = event.request.clone();
const methodsToReply = ['POST', 'PUT', 'DELETE']
if (methodsToReply.includes(requestClone.method)) {
event.respondWith(
(() => {
const promiseChain = fetch(requestClone).catch(() => {
return bgSyncQueue.pushRequest(event);
});
event.waitUntil(promiseChain);
return promiseChain;
})()
);
} else {
event.respondWith(fetch(event.request));
}
};
async function syncData() {
console.log('sync data running');
let entry;
while ((entry = await bgSyncQueue.shiftRequest())) {
try {
console.log('sync data running', entry);
await fetch(entry.request);
console.error("Replay successful for request", entry.request);
} catch (error) {
console.error("Replay failed for request", entry.request, error);
// Put the entry back in the bgSyncQueue and re-throw the error:
await bgSyncQueue.unshiftRequest(entry);
throw error;
}
}
console.log("Replay complete!");
}

Svelte (Express & Axios) - http 500 error on put method

I'm at a loss. I have a svelte application (Backend: Express, Frontend: Axios). I have a MongoDB with locations. Locations have an array of bands. And I want to add bands to this array. The backend seems to work fine, at least with Postman it works. But when I try to add a band through the frontend, I get a http 500 error.
This is the back end code:
app.put('/api/locations/:location', async (req, res) => {
let location = req.params.location;
let updatedlocation = req.body;
try {
await client.connect();
const database = client.db('Concerts');
const collection = database.collection('locations');
const query = { locationname: location };
const result = await collection.updateOne(query, { $set: updatedlocation });
if (result.matchedCount === 0) {
let responseBody = {
status: "No Location under the name " + location
}
res.status(404).send(responseBody);
}
else {
res.send({ status: "Location " + location + " has been updated." });
}
} catch (error) {
res.status(500).send({ error: error.message });
}})
This is the method in the frontend:
function addConcert() {
location.concerts.push(chosenband);
console.log("http://localhost:3001/api/locations/" +name);
console.log(location);
axios.put("http://localhost:3001/api/locations/" +name, location)
.then((response) => {
alert("Konzert wurde hinzugefĆ¼gt");
})
.catch((error) => {
alert("Nope");
console.log(error);
});
}
Info: the {chosenband} comes from a select. This seems to work as well, as the console logs show.
The object is correct and includes the new band:
this is the log from the browser
So the object seems fine. Also the put-url is correct.
But I always get this 500 error
Thankful for any advise!
Found the problem. I didn't instantiate the location correctly. First I instantiated it simply as
let location = {}
, that didn't work. When I instantiated it with all the attributes
let location = {example:"", second:""}
it worked. Thanks for your help

facebook login working on development mode or server mod, when create a build, it's not working on any devices. react native app

feature unavailable facebook login in currently unavailable for this app, since we are updating additionl details for this app. please try again later
working only on my system and device, not working in others,
how to resolve this issue,please help
FacebookSignIn = async () => {
// Attempt login with permissions
try {
const result = await LoginManager.logInWithPermissions(['public_profile', 'email']);
console.log("fb login", result)
if (!result.isCancelled) {
await AccessToken.getCurrentAccessToken()
.then(async res => {
console.log("token", res);
// Create a Firebase credential with the AccessToken
const facebookCredential = auth.FacebookAuthProvider.credential(res.accessToken);
console.log("token", res);
// Sign-in the user with the credential
this.setState({ loder: true })
await auth().signInWithCredential(facebookCredential)
.then(response => {
console.log("Login Data", response);
const data = {
"name": response.additionalUserInfo.profile.first_name,
"email": response.additionalUserInfo.profile.email,
"user_type": 0
}
console.log(data);
fetchPostMethod('/facebook-sign-up', data)
.then(async response => {
this.setState({ loder: false })
if (response.status == 200) {
if (response.data.user_type == 0) {
try {
let user = JSON.stringify(response?.data?.user_type)
await AsyncStorage.setItem('SignINToken', response?.data?.token);
await AsyncStorage.setItem('UserType', user);
this.logmodl();
} catch (e) {
console.log("Login error", e)
}
} else {
this.user();
}
console.log("SignIn Successful", response);
} else {
this.field();
}
})
.catch(response => {
this.setState({ loder: false })
console.log("SignIn faild", response.message);
})
this.setState({ FacebookUserInfo: response });
})
.catch(error => {
console.log('Login Data Error', error);
})
})
.catch(error => {
console.log('Something went wrong obtaining access token ', error);
})
}
} catch (error) {
console.log("ERROR WHILE LOGIN! ", error);
}
}
feature unavailable facebook login in currently unavailable for this app, since we are updating additionl details for this app. please try again later
working only on my system and device, not working in others,
how to resolve this issue,please help
Pay attention! For enable Facebook login for other users you need visit the Facebook developer site
and enable work mode for application, moving this switch

React-native axios with ColdFusion component

I'm trying to send a get request from react native, using axios, to my coldfusion component.
My coldfusion component:
component displayName="react" {
remote any function ajaxLogin(data) returnformat="JSON"{
data = deserializeJSON(arguments.data);
return serializeJSON(login(data));
}
private any function login(data){
loginQuery = new query();
loginQuery.setDatasource("ds");
loginQuery.setName("loginQuery");
loginQuery.addParam(name="UserEmail", value="#arguments.data.userEmail#", cfsqltype="cf_sql_varchar");
loginQuery.addParam(name="UserPW", value="#arguments.data.userPassword#", cfsqltype="cf_sql_varchar");
result = loginQuery.execute(sql="SELECT * FROM Users Where UserEmail = :UserEmail AND UserPW = :UserPW");
rs = result.getResult();
if(rs.recordCount == 0){
return 0;
} else {
return rs.UserID;
}
}
}
My react-native dispatch action:
export const loginUser = ({ email, password }) => {
// login
return (dispatch) => {
dispatch({ type: 'TEST' });
axios.get('https://myserver.com/components/reactNative/react.cfc?method=ajaxLogin', {
params: {
userEmail: email,
userPassword: password
}
})
.then((response) => {
console.log(response.data);
})
.catch((err) => {
console.log(err);
});
};
};
It is returning an error from the catch:
Error: Request failed with status code 500
I am new with axios and react-native. Am I using axios wrong?
Thanks
Status code 500 is a server-side error so you're likely getting a Coldfusion error, check your ColdFusion logs.
Also as you're calling this as a GETrequest you can just open the URL in a browser tab and see if you get any errors dumped to the page (in a development environment)
https://myserver.com/components/reactNative/react.cfc?method=ajaxLogin&userEmail=email&userPassword=password
If this is production then you should see errors in your error logs (somewhere like /var/www/opt/coldfusion_11/cfusion/logs on linux)

when i fetch data from api using for loop i am getting error in react native

async makeRemoteRequestNotification() {
var backapi = api.Backend_API();
let userId = await AsyncStorage.getItem("userid");
fetch(backapi + "event/notification/" + userId, {
method: "GET",
}).then((response) => response.json())
.then((data) => {
for(let i in data){
fetch(backapi+"event/eventname/"+data[i].event_id,{
method:'GET',
}).then((response)=>response.json())
.then((data)=>{
this.state.data.push(data)
console.log("notification event",this.state.data);
})
console.log("created_by",data[i].created_by);
fetch(backapi+"user/getUserById"+data[i].created_by,{
method:'GET'
}).then((response)=>response.json())
.then((data)=>{
console.log("username",data);
})
}
// this.state.data=data;
console.log("clint",this.state.data);
})
};
getting error as
Unhandled Promise Rejection (id: 0): SyntaxError: Unexpected token C
in JSON at position 0
You should check the status of you response before .then((response) => response.json())
For example you can do:
.then((response) => {
if (response.status == 200) {
//Deal with your response and do whatever you want
}
else {
//do somthing with your error status
}
})
Your question is not related to react native. You are getting error when trying to parse an invalid json response (or not json at all). Use debug tools to catch the incorrect server response and use the catch block in promise chain to process such situations.