我想在用户登录失败时显示一条警告消息。但是没有显示警告。以下是我在 React 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
但它不会在登录不成功时发出警报。当我安慰我时,我遇到了 unexpected end of json input error 但我我正在使用 Node js 作为后端,错误结果显示如下是我在 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
的控制台结果是
{ error: 1, data: 'Phone number does not exist' }
我不知道为什么这个错误消息没有显示在 react native 的 responseData
中。
最佳答案
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));
});
}
始终在 promise 的末尾使用“catch”并处理它们。
如果您仍然遇到这个问题,请告诉我。
关于javascript - 在 React Native 中登录凭据无效时如何显示警报消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53077076/