Possible Unhandled Promise Rejection / Error: Request failed with status code 400 - react-native

I know there are some answers on this and I read them all. But none of them helped.
So this is my error message:
And here is my action:
export function registerUser(data){
const request = axios({
method: "POST",
url: `${REGISTER}${API_KEY}`,
data: {
email: data.email,
password: data.password,
},
headers:{
"Content-Type":"application/json"
}
}).then(response => response.data)
return {
type: "REGISTER_USER",
payload: request,
}
}
Thanks!

Give a try to fetch the library for making API call.
function registerUser(data){
return fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers:{
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then((apiResponse)=>{
console.log("api response", apiResponse)
return {
type: "REGISTER_USER",
api_response: apiResponse.data
}
})
.catch(function (error) {
return {
type: "REGISTER_USER",
api_response: {success: false}
}
})
}
Invoking the above function
let data = {
email: "youremail#gmail.com,
password:"yourpassword"
}
registerUser(data).then((response)=>{
console.log(response)
})

Log error and succes then check:
export function registerUser(data){
const request = axios({
method: "POST",
url: `${REGISTER}${API_KEY}`,
data: {
email: data.email,
password: data.password,
},
headers:{
"Content-Type":"application/json"
}
})
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})

You should use catch handler wherever you call an api with a promise, because you don't when the api will fail and you have to handle the error.
export function registerUser(data){
return axios({
method: 'post',
url: `${REGISTER}${API_KEY}`,
data: {
email: data.email,
password: data.password,
},
headers: {
'Content-Type': 'application/json'
}})
.then(function (response) {
//handle success
return {
type: "REGISTER_USER",
payload: response.data,
}
})
.catch(function (err) {
//handle error
return {
type: "REGISTER_USER_FAILED",
payload: null
}
});
}
Call the function like this
const data = {
email: 'asd#asd.asd',
password: 123
}
registerUser(data).then((response)=>{
console.log(response)
})

export function registerUser(data){
return axios({
method: "POST",
url: `${REGISTER}${API_KEY}`,
data: {
email: data.email,
password: data.password,
},
headers:{
"Content-Type":"application/json"
}
}).then((api_response)=>{
return {
type: "REGISTER_USER",
api_response: api_response.data
}
}).catch(function (error) {
return {
type: "REGISTER_USER",
api_response: {success: false}
}
})
}
//Invoking the above function
let data = {
email: "youremail#gmail.com,
password:" password"
}
registerUser(data).then((response)=>{
console.log(response)
})

Related

How to fetch token in a function block

i create a working heroku app from here
when i send to
heroku app url/rtc/:channelName/:role/:tokentype/:uid/?expiry=
i get the token fine.
but how to do this in function block?
like the one from here
function fetchToken(uid, channelName, tokenRole) {
return new Promise(function (resolve) {
axios.post('http://<Your Host URL and port>/fetch_rtc_token', {
uid: uid,
channelName: channelName,
role: tokenRole
}, {
headers: {
'Content-Type': 'application/json; charset=UTF-8'
}
})
.then(function (response) {
const token = response.data.token;
resolve(token);
})
.catch(function (error) {
console.log(error);
});
})
}

undefined response from axios.post

when i try to make a post request i get a network error, with an error.message of 'undefined'
here's the setup:
export default axios.create({
baseURL: API_HOST,
withCredentials: true,
crossdomain: true,
});
and the actual call:
export const Login = (email, password) => dispatch => {
axios
.post('/v1/login?', {email, password})
.then(response => {
console.log('yes');
token = () => {
return response.token ? response.token : '';
};
dispatch({
type: UPDATE_AUTH_PROPS,
payload: [
{prop: 'errorMessage', value: 'successed'},
{prop: 'token', value: token},
],
});
})
.catch(error => {
debugger;
dispatch({
type: UPDATE_AUTH_PROPS,
payload: [{prop: 'errorMessage', value: error.message}],
});
});
};
Try this, this is easy and readable...
axios
.post(api_url + '/v1/login?', data, {
'Content-Type': 'application/json',
})
.then(
res => {
alert('Response');
},
error => {
alert('Error');
},
);
}
};

How to show network error message in react native

I have a react native function which uses the fetch function to post some data. The problem is I can't alert the response error message. My error code is 400. this is my code:
fetch(conf.getsignUpURL(), {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
})
.then(function (response) {
if (!response.ok)
{
let error = new Error(response.statusText);
throw error;
}else
{
return response.json();
}
})
.then(async function (data) {
//something
}).catch( (error) => {
alert(error.message);
});
After the run, it will alert empty.
fetch(conf.getsignUpURL(), {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
})
.then(function (response) {
// Here I added the alert
alert(JSON.stringify(response))
if (!response.ok)
{
let error = new Error(response.statusText);
throw error;
}else
{
return response.json();
}
})
.then(async function (data) {
// Here I added the alert
alert(JSON.stringify(data))
//something
}).catch( (error) => {
alert(error.message);
});

how can we get post data from fetch function in react native to express api?

Question:
How can we get post data from fetch function in react native to express api?
Issue Faced:
I tried the following process but didn't got those variables in back-end API.
How can the variables be achieved in the backend API? Any suggestions are highly appreciated.
Here is the reactive native fetch function:
REACT NATIVE FETCH FUNCTION:
login = async () => {
await fetch('http://192.168.1.160:8001/api/login', {
method: 'POST',
mode: 'cors',
cache: 'default',
header: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password
})
})
.then ((response) => response.json())
.then ((res) => {//console.log(res);
if(res.error === false){
AsyncStorage.setItem('user', res.data);
this.props.navigation.navigate('profile');
} else{
// alert(res.message);
}
})
}
Express-API:
The express API is given below:
module.exports = function (req, res) {
console.log('TEST',req.body);
let { email, password } = req.body;
let input = { email, password };
const validator = loginValidator(input);
if (validator.error) {
return res.status(400).json({
error: true,
message: validator.error.details,
});
} else {
models.users.findOne({
where: { email: email }
}).then(user => {
if (!user) {
return res.status(400).json({
error: true,
message: {
key: 'email',
text: MessageHelper.email_already_exist
}
});
} else if (!bcrypt.compareSync(password, user.password)) {
return res.status(400).json({
error: true,
message: {
key: 'password',
text: MessageHelper.password_not_valid
}
});
} else {
var token = jwt.sign({ userid: user.id },Config.get('jwt.privatekey'));
models.users.update({ token: token },{ where: { id: user.id } }).then(function(result){
return res.json({
error: false,
message: MessageHelper.user_token_updated,
token: token,
data: {
user_id: user.id,
firstname: user.firstname,
lastname: user.lastname,
username:user.username,
email: user.email,
mobile: user.mobile,
token: user.token
}
});
}).catch(function(error){
return res.status(400).json({
error: true,
message: error
});
})
}
});
}
}
Fetch also takes an optional second argument that allows you to
customize the HTTP request. You may want to specify additional
headers, or make a POST request:
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
});
Networking is an inherently asynchronous operation. Fetch methods will
return a Promise that makes it straightforward to write code that
works in an asynchronous manner:
function getMoviesFromApiAsync() {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
}

await is giving Refrence error in react-native

I have the following code
async _onPress() {
NetInfo.isConnected.fetch().then(isConnected => {
if (isConnected) {
fetch(apiURL + '/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: this.props.username,
password: this.props.password
})
})
.then((response) => response.json())
.then((responseJson) => {
if (responseJson.status === 'success')
//I am getting error here
await AsyncStorage.setItem('token', responseJson.token);
//moving on to the main screen if server return success
Actions.MainScreen();
} else {
Toast.show({
text: "Wrong username or password!",
type: "danger"
});
}
})
.catch((error) => {
console.log(error);
});
} else {
Toast.show({
text: "Please Connect To Internet",
type: "danger"
});
}
});
}
I am trying to save the token i receive from my API server using AsyncStorage.I get the following errors
Expression statement is not assignmentor call
and RefrenceError:await is not defined
when i try to use await in the location.
But when use the same code at the beginning of the function i get no errors.
I dont know what is wrong. Is it not allowed in async await? I am not too familiar with these.
If _onPress calls some async functions and you want to wait for all of them to finish, you must place an 'await' in front of every single one of them. In addition, every async function, including async callback functions, must be declared async too.
The complete code:
async _onPress() {
**await** NetInfo.isConnected.fetch().then(**async** (isConnected) => {
if (isConnected) {
**await** fetch(apiURL + '/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: this.props.username,
password: this.props.password
})
})
.then((response) => response.json())
.then(**async** (responseJson) => {
if (responseJson.status === 'success') {
**await** AsyncStorage.setItem('token', responseJson.token);
Actions.MainScreen();
} else {
Toast.show({
text: "Wrong username or password!",
type: "danger"
});
}
})
}
})
}