I am trying to make a fetch API call to a new Firebase instance with my React-Native app, but I am running into this error:
Possible Unhandled Promise Rejection (id: 0):
Network request failed
TypeError: Network request failed
at XMLHttpRequest.xhr.onerror (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:25119:8)
at XMLHttpRequest.dispatchEvent (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:10405:15)
at XMLHttpRequest.setReadyState (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:26688:6)
at XMLHttpRequest.__didCompleteResponse (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:26536:6)
at http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:26630:52
at RCTDeviceEventEmitter.emit (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:9638:23)
at MessageQueue.__callFunction (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:7493:34)
at http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:7375:8
at guard (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:7306:1)
at MessageQueue.callFunctionReturnFlushedQueue (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:7374:1)
The functions look like so:
getNotes(username){
username = username.toLowerCase().trim();
var url = `https://myproject-6342.firebaseio.com/${username}.json`;
return fetch(url).then((res) => res.json());
},
addNote(username, note){
username = username.toLowerCase().trim();
var url = `https://myproject-6342.firebaseio.com/${username}.json`;
return fetch(url, {
method: 'post',
body: JSON.stringify(note)
}).then((res) => res.json());
}
What is going wrong here?
The promise from the fetch API will reject with a TypeError when a network error occurs, which means you have to handle the error. Example:
function _handleError(errorMessage) {
console.log(errorMessage);
}
fetch('https://api.github.com/users/octocat/repos').then(function(response) {
if(response.ok) {
return response.json();
} else {
_handleError(`Oops, something went wrong: ${response.status}, ${response.statusText}`);
}
}).then(function(data) {
if(data) {
console.log('success', data);
}
}).catch(function(error) {
_handleError(`There has been a problem with your fetch operation: ${error.message}`);
});
More info here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Checking_that_the_fetch_was_successful
Well in my case the emulator internet was not working, I followed the below thread to make that work.
Android emulator not able to access the internet
Related
I have just started exploring axios and using interceptors
In my code, I have axios api call here and there, So I used interceptors to handle error,
but it still show uncaught error in my console. I dont know why is that?
For example, this is my api code:
export const getcountryAllocations = async (country: string) => {
const response = await instance.get<IcountryAllocationTypeResponse[]>(
`/asa/${country}`
)
return response.data
}
So, in order to handle error in a centralized way, I used interceptors to handle error.
export const instance = axios.create()
instance.interceptors.response.use(
res => {
return res
},
error => {
if (error.response.status === 401) {
console.log(error)
}
throw error
}
)
But I still get a red error in console when I get api request error, say the example api I mentioned above
GET http://localhost:30087/asa/USD 401 (Unauthorized)
AxiosError {message: 'Request failed with status code 401', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
localhost/:1 Uncaught (in promise) AxiosError {message: 'Request failed with status code 401', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
But I expect that it shouldnt display localhost/:1 Uncaught anymore, as I have handled it in interceptors
You are catching the error but then throwing it again. That's why you still have the red error in the console.
What you can do is catch the error and then return an object saying an error occurred without throwing it again.
export const instance = axios.create()
instance.interceptors.response.use(
res => {
return res
},
error => {
if (error.response.status === 401) {
console.log(error)
}
return {
success: false,
message: error.message,
status: error.response.status
}
}
)
I am running this code and testing with no internet connection:
fetch(url, options)
.then(res => {
// irrelevant, as catch happens immediately on no network connection
})
.catch(err => {
console.log('Failed fetch ', err);
});
What does the 'TypeError' mean?
From you snippet, it should log
Failed fetch TypeError: ...
and TypeError are throw when fetch not success
more information please check
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Checking_that_the_fetch_was_successful
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
A fetch() promise will reject with a TypeError when a network error is encountered.
plus,the first then get a resolved promise object.You should use then after like this:
fetch(url, options)
.then(res =>res.json())
.then(data=>{console.log('data from server',JSON.stringify(data))})
.catch(err => {
console.log('Failed fetch ', err);
});
Checking that the fetch was successful
I am running my react native code on expo client. When I try to fetch from google.com, for instance, I get
"TypeError: Network request failed"
error.
I have internet on my device.
This error message does not make sense in detail. How can I understand the real problem beneath.
static test(provider, token, success, error) {
console.log(1); // TODO: remove
fetch("https://wwww.google.com", {
method: "GET",
})
.then(response => {
console.log(2); // TODO: remove
if (response.ok) {
success(response);
} else {
error(response);
}
}).catch(e => {
console.log("RestService Error: " + e);
});
}
Update:
Snack added.
https://snack.expo.io/#dijkstras/fetch-issue
You added 4 'wwww' in url address.
fixed snack:
https://snack.expo.io/#djalik/fetch-issue
I have a React Native application that I cloned. It connects with MongoDB using Node.js API. However, after registering into the app it cannot insert nor fetch the data from MongoDB. Also, on my simulator, I got a yellow error at the bottom of the screen which says:
Possible Unhandled Promise Rejection (id: 0): TypeError: undefined is not an object (evaluating 'err.response.data')
Here is my code:
export const loginuser = userData => dispatch => {
axios.post("http://localhost:4000/api/users/login", userData)
.then(res => {
// save user token to local storage
const { token } = res.data;
AsyncStorage.setItem("jwtToken", token);
console.log(AsyncStorage.setItem())
// set token to auth header i.e authorization
setAuthToken(token);
// decode the token and saveuser to deoded
const decoded = jwt_decode(token);
console.log(token)
//set current user
console.log(decoded)
dispatch(setCurrentUser(decoded));
Actions.main()
})
.catch(err => dispatch({
type:GET_ERRORS,
payload: err.response.data
})
)
}
May i know the best solution to solve this error.
Hope for your help. Thank you
Please check with Axios document on how to handle errors:
https://github.com/axios/axios#handling-errors
err.response might be empty:
axios.post("http://localhost:4000/api/users/login", userData)
.catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});
Below is my connection request code :
doLogin(this.login).then(response => {
var token = response.data.token;
localStorage.setItem('AUTH_TOKEN', JSON.stringify(token));
this.$router.push({name: 'Devices'});
});
}).catch(error => {
console.log(error.response.data.message);
});
the catch() part works fine for http errors (like 400, 404, 403..etc). But when my server is offline this script just throws net::ERR_CONNECTION_REFUSED. Is there any way to handle this error and let the front-end user know that the server is currently offline.?
Here is the doLogin() function just in case,
function doLogin(data) {
const url = 'http://localhost:3000/authenticate';
return axios.post(url,data);
}
You can try this in the catch part:
catch(error => {
if (!error.response) {
// network error
this.errorStatus = 'Error: Network Error';
} else {
this.errorStatus = error.response.data.message;
}
})
You may use interceptors:
axios.interceptors.response.use(
response => {
return response
},
error => {
if (!error.response) {
console.log("Please check your internet connection.");
}
return Promise.reject(error)
}
)
You should do the same validation that #chithra pointed out in the .then() because i'm having a weird issue when testing requests with my servers down, the "response" comes as if it was a success.
Also, on the .then() do it with response.status instead of response.error
By using npm; a standard package manager for the JavaScript runtime environment Node.js.
With npm:
npm i axios
Next, you should import Axios in your src/App.vue file
import axios from 'axios';
you will need to call it on a lifecycle hook. Here we will use the beforeCreated() lifecycle hook, this is because we will be able to retrieve sensitive data and events that are active with the beforeCreated hook.
data() {
return {
network: false,
}; },
beforeCreate() {
axios
.get("http://localhost:13172/api/product/getproducts")
.then((response) => {
console.log(response);
this.network = true;
})
.catch((error) => {
console.log(error), (this.network = false);
}); }