Я хочу показать предупреждающее сообщение при неудачной попытке входа в систему. Но предупреждение не отображается. Следующим является мой код в редакторе native.
авторизоваться
onPressLogin(){
fetch('http://192.168.1.10:3000/users/login',{
method: 'POST',
headers:{
'Content-Type' : 'application/json',
'Accept':'application/json'
},
body: JSON.stringify({
contact:this.state.contact,
password: this.state.password,
})
})
.then(response => response.json())
.then((responseData) =>
{
this.setState({
userdetail: responseData,
})
if(responseData){
setTimeout(() => {
Actions.firstScreen();
}, 2300);
AsyncStorage.saveItem('userid', this.state.userData.phone_no);
} else {
console.log(responseData);
Alert(responseData);
}
});
}
То, что я получаю сейчас, это перенаправление на firstScreen
при успешном входе в систему, но это предупреждение не приходит на неудачный логин. Когда я утешаюсь, я получаю неожиданный конец ошибки ввода json, но я использую узел js в качестве backend результата ошибки показывает, что следующий мой код в nodejs
else {
appData.error= 1;
appData["data"] = "Phone number and Password does not match";
res.status(204).json(appData);
console.log(appData);
}
}else{
appData.error=1;
appData["data"] ="Phone number does not exist";
res.status(204).json(appData);
console.log(appData);
}
appData
результатом appData
является
{ error: 1, data: 'Phone number does not exist' }
Я не знаю причину, почему это сообщение об ошибке не отображается в responseData
в responseData
native.
onPressLogin(){
fetch('http://192.168.1.10:3000/users/login',{
method: 'POST',
headers:{
'Content-Type' : 'application/json',
'Accept':'application/json'
},
body: JSON.stringify({
contact:this.state.contact,
password: this.state.password,
})
})
.then(response => response.json())
.then((responseData) =>{
if(responseData.error !== 1){ // verify the success case, as you didn't provide the success case i am using the error code
this.setState({ // its recommended you verify the json before setting it to state.
userdetail: responseData,
})
setTimeout(() => {
Actions.firstScreen();
}, 2300);
AsyncStorage.setItem('userid', this.state.userData.phone_no); // its setItem not saveitem.
} else {
console.log(responseData);
Alert.alert(JSON.stringify(responseData)); // Alerts doesn't allow arrays or JSONs, so stringify them to view in Alerts
}
}).catch((error) => {
// handle catch
console.log("error:"+JSON.stringify(error));
});
}
Всегда используйте "catch" в конце обещаний и обрабатывайте их.
Дайте мне знать, если вы все еще сталкиваетесь с проблемой.