首页 > 解决方案 > 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.

标签: validationreact-native

解决方案


我已经根据验证用户名/密码正确/错误的状态编写了这样的代码。所以如果它对将来的任何人有用,这里将发布代码。下面的代码是,

 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;
    }

推荐阅读