当服务器向客户端返回错误消息时,如何显示警报框。如果响应无效,但警报没有来临,我已经做了一些显示警报框的操作。服务器中的错误消息也在控制台内显示为unexpected end of json input
。但是,成功情况也在显示。成功情况为{error:0 , token:zxrggsdhsgdjcbuewy656}
nodjs
users.post('/ login',function(req,res){
var appData ={};
var phone_no = req.body.contact;
var pwd = req.body.password;
database.connection.getConnection(function(err,connection){
if(err){
appData["error"] =1;
appData["data"] ="Internal Server Error";
res.status(500).json(appData);
}else{
connection.query("SELECT * FROM user_registration WHERE phone_no = ?",[phone_no],function(err,result,fields){
if(err){
appData.error = 1;
appData["data"] = "Error Occured";
res.status(400).json(appData);
console.log(result);
} else {
if(result.length >0) {
if(result[0].pwd == pwd){
let token = jwt.sign(result[0], process.env.SECRET_KEY,{
expiresIn :5000
});
appData.error =0;
appData["token"] =token;
res.status(200).json(appData);
//console.log(appData);
} 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);
}
}
});
connection.release();
}
});
还有反应部分如下
onPressLogin(){
fetch('http://192.168.1.7:3000/users/login',{
method: 'POST',
headers:{
'Content-Type' : 'application/json',
},
body: JSON.stringify({
contact:this.state.contact,
password: this.state.password,
})
})
.then(response => response.json())
.then((responseData) =>
{
this.setState({
userdetail: responseData,
})
console.log(responseData);
if(responseData.error == '0'){
setTimeout(() => {
Actions.firstScreen();
}, 2300);
AsyncStorage.setItem('userdetail', this.state.userdetail.token);
AsyncStorage.getItem('userdetail').then((value) => console.log(value));
} else {
Alert.alert(
'Alert',
'Invalid Login',
[
{text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
{text: 'OK', onPress: () => console.log('OK Pressed')},
],
{ cancelable: false }
)
}
});
}
请帮助