React Native - 发送信息以接收简单登录屏幕的响应,但接收 JSON 解析错误

嘉莉

我已经多次尝试发送数据并接收响应,但它似乎没有发送用户输入的数据。我已经尝试以多种方式解决这个问题,我将分享最后两个的代码。

state = {
    phoneNo: '',
    pin: '', 
    isLoggingIn: false, 
    message: ''
  }

  _userLogin = () => {
     console.log("userLogin");
    this.setState({isLoggingIn: true, message:''});

    var params = {
      phoneNo: this.state.phoneNo,
      pin: this.state.pin

    };



        var proceed = false;
        fetch("https://"+"<url>", {
                method: "POST",
                headers: {
                      'Accept': 'application/json',
                      'Content-Type': 'application/json'
                },
                body: JSON.stringify(params)
            })
            .then(
              (response) => response.json())
            .then((response) => {
                if (response.status == 200) {

                    proceed = true;
                   }
                else {


                    this.setState({ message: response.message });
                    console.log(message); }
            })
            .then(() => {
                this.setState({ isLoggingIn: false })
                if (proceed) this.props.onLoginPress();

            })
            .catch(err => {
              console.log(err.message); 

        this.setState({ message: err.message });
        this.setState({ isLoggingIn: false })
      });
    }

两个这里唯一的区别是我如何处理响应,所以我只会添加该部分。我认为这个问题可能是由于此时的语法。

.then(function(response){ 
 return response.json();   
 })
.then(function(data){ 
 console.log(data)

我已经通过各种教程、github 和 stackoverflow 页面解决了这个问题,但我似乎遗漏了一些东西。我不断收到 JSON 解析错误,并且我确信数据可能永远不会发送到 url,因为无论用户输入如何,我都会收到错误消息。

两个输入字段都有一个 ref,按钮指向用户登录功能。

       <TextInput 
        ref = {component => this._pin = component}
        placeholder="pin" 
        onChangeText = {(pin) => this.setState({pin})}
        secureTextEntry = {true}
        onSubmitEditing={this._userLogin}

        />

        <TouchableOpacity 
         onPress={this._userLogin}
         title = "Submit"
         disabled={this.state.isLoggingIn||!this.state.phoneNo||!this.state.pin}>
          <Text style={styles.loginText}>Sign In</Text>
        </TouchableOpacity>
嘉莉

AlainIb 非常有帮助,这有助于最终的工作。使用表单数据似乎有助于解决 JSON 解析错误。希望这可以帮助其他遇到任何麻烦的人。

    state = {
    message: ''
  }

_processResponse = (response) =>{
    const statusCode = response.status;
      console.log("resp", response); 
  const data = response.json();
  console.log("data", data); 
  return Promise.all([statusCode, data]).then(res => {
    return ({
      statusCode: res[0],    // the status code
      data: res[1]           // the data of the GET/POST returned by fetch call 
    })
  });
}

_userLogin = () => {
    console.log("userLogin");
    this.setState({isLoggingIn: true, message:''});

    var params = {
     phoneno: this.state.phoneno,
      pin: this.state.pin
    };

      var formData = new FormData();
      formData.append("phoneno", this.state.phoneno);
      formData.append("pin", this.state.pin);
      console.log(formData);

let data = {
    method: 'POST',
    headers: {
        'Accept': 'application/json',

                  'Content-Type':'multipart/form-data'
    },
    body: formData
}
    console.log(data);

  fetch("https://"+"url", data)
        .then(this._processResponse) 
        .then(res => {
          console.log("response of fetch",res);  
          const { statusCode, data } = res;
          if (statusCode == 200) {
             console.log("in if statement"); 
         if(data.login_success== 1){
            console.log("name to be passed", data.name);
            console.log("log in to profile");
            this.props.navigation.navigate('ProfileRoute');

         }else {
             console.log("fail"); 
             this.setState({message:"Password or Phone Number is Wrong"});
         }
          }else{
            this.setState({ message: data.message });
            console.log("data message" , data.message); 

          }
          this.setState({ isLoggingIn: false })
        })
        .catch(err=> {
          console.error(err);
          this.setState({ message: err.message});
          this.setState({isLoggingIn: false})
        });
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

JSON解析错误:无法识别的令牌'<'-react-native

JSON解析错误:无法识别的令牌“ <”-React Native

React Native:包解析错误

在React Native中解析对FlatList的JSON数组响应

React Native API json 解析数据错误:未处理的承诺拒绝:SyntaxError:JSON 解析错误:无法识别的令牌“<”

Stipe,React Native,[未处理的承诺拒绝:SyntaxError:JSON 解析错误:意外的标识符“错误”]

处理JSON响应React Native

React Native 中的 JSON Fetch 解析问题

JSON解析错误:意外标识符“未定义”(React Native)

JSON 解析错误:使用 fetch 向后端发送请求时,React Native App 上出现意外标识符“隧道”

错误:无法解析模块`buffer` React Native

React Native 错误:无法解析模块`./index`

react-native:解析错误:意外的令牌<

React Native 错误“无法解析模块‘react-native’”

React-Native:每 X 秒解析一次简单的 JSON GET/POST 和刷新

React Native 显示简单的 Json 数据

加载Json对React Native下拉列表的响应

React Native 检查来自 api 的 json 响应

React Native - 返回响应错误代码:500 - 无法解析模块。这可能与错误 react-native/issues/4968 有关

在 React Native fetch 方法中解析 JSON 不起作用

如何在React Native中解析JSON数据

解析JSON以在React Native中建模未定义

React Native,Map JSON

React Native Cant Find Variable简单错误

React Native Init错误找不到模块-> node_modules \ react-native \ package.json'

如何使用react-native解决“无法解析模块...”错误?

错误:无法解析模块“ react-native-gesture-handler”

错误:无法解析模块react-redux / native

使用Atom和React Native的ESLint意外解析错误