validation - React Native:提交时如何验证用户名和密码
问题描述
我已经验证了用户名和密码,如果用户名和密码错误,那么我想通过像“无效的用户名/密码”这样的错误。如果有人知道,请告诉我。
async submit() {
//Validating username and password
const { username, password } = this.state;
if(username == ''){
this.setState({error:'Username is required'});
} else if(password == ''){
this.setState({error:'Password is required'});
} else {
this.setState({error: null})
let collection={};
collection.username=this.state.username;
collection.password=this.state.password;
// console.warn(collection);
var url = 'my url';
try {
let response = await fetch(url,
{
method: 'POST', // or 'PUT'
body: JSON.stringify(collection), // data can be `string` or {object}!
headers: new Headers({
'Content-Type': 'application/json'
})
});
let res = await response.text();
// console.warn(res);
if (response.status >= 200 && response.status < 300) {
//Handle success
let accessToken = res;
console.log(accessToken);
//On success we will store the access_token in the AsyncStorage
this.storeToken(accessToken);
// console.warn(accessToken);
//After storing value,it will navigate to home
this.props.navigation.navigate('Home');
} else {
//Handle error
console.log('Success:',response);
let error = res;
throw error;
}
} catch(error) {
console.log("error " + error);
}
}
}
给出无效用户名/密码后的响应:
0 {…}
field :password
message :Incorrect username or password.
解决方案
我已经根据验证用户名/密码正确/错误的状态编写了这样的代码。所以如果它对将来的任何人有用,这里将发布代码。下面的代码是,
if (response.status >= 200 && response.status < 300) {
//Handle success
let accessToken = res;
//On success we will store the access_token in the AsyncStorage
this.storeToken(accessToken);
console.warn(accessToken);
//After storing value,it will navigate to home
this.props.navigation.navigate('Home');
} else {
console.log('Success:',response);
this.setState({error:'Invalid username/password'});
let error = res;
throw error;
}
推荐阅读
- google-sheets - 如何从其他工作表导入数据并列出它们?
- ruby-on-rails - Rails Fixtures 未定义的方法
- r - 在 RStudio 中查看“.RData”文件数据的命令是什么?
- css - 为什么我的 css 类没有加载?
- ruby-on-rails - 将 RDS 从 EB 转移到新账户
- javafx - 如何在舞台顶部添加标签
- javascript - Hapi.js 17.xx:如何从处理函数返回响应而不返回
- ubuntu - blk_update_request:I/O 错误,dev sda,扇区 xxxxxxxxxxx
- javascript - 在 IIFE 上使用 .call(this)
- raspberry-pi - 如何使用 Android Things 获得 LV-MaxSonar LV-EZ0 测距仪的每个规格输出?