首页 > 解决方案 > 反应原生的pots API [object object]

问题描述

我在向服务器发送数据时遇到问题。当我尝试使用以下响应通过邮递员成功提交数据并且如果我激活“Content-Type”:“application / json”

我有一个问题是 JSON Parse 错误:无法识别的令牌 '<'

{
    "status": 200,
    "message": "success login",
    "id_kurir": "3",
    "username": "tester",
}

当我尝试使用代码时,我收到一个错误,即 [object object]

这是我的代码:

constructor(props) {
    super(props);
    this.state = {
      Uname : '',
      Upass : ''
    }
  }

  login= ()=>{
    const {Uname,Upass} = this.state;
    fetch('https://example.com/login', {
      method: 'POST',
      // headers: {
      //   'Accept' : 'application/json',
      //   'Content-Type': 'application/json'
      //},
              body: JSON.stringify({
              username: Uname,
              password: Upass
            })
      })
      .then((response) => response.json())
      .then((responseJson) => {
          alert(responseJson);
          console.log(JSON.stringify(responseJson));
        }).catch((error)=>{
          console.log(error);
        })
      Keyboard.dismiss();
  }



           <Form style={styles.mainForm}>
              <Item style={styles.formItems}>
                <Input placeholder="Username" style={styles.Input} onChangeText={Uname => this.setState({Uname})}/>
              </Item>
              <Item style={styles.formItems}>
              <Input style={styles.Input} secureTextEntry={true} onChangeText={(Upass) => this.setState({Upass})}/>
              </Item>

              <View style={styles.Button}>
                {/* <Button block style={styles.mainBtn} onPress={() => this.props.navigation.navigate('home')}> */}
                <Button block info style={styles.mainBtn} onPress={this.login}>
                  <Text style={styles.btnText}>Submit</Text>
                </Button>
              </View>
            </Form>

错在哪里?

标签: javascriptreactjsapireact-native

解决方案


服务器可能出现 404 或 500 错误。而不是 response.json() 使用 response.text() 您将获得文本中的 html。

我假设您的服务器没有采用 JSON 格式的正文

尝试使用下面的代码。

选项1:

fetch('https://example.com/login', {
    method: 'POST',
    body: JSON.stringify({
        username: Uname,
        password: Upass
    })
}).then(response => response.text()).then((text) => {
  if (Platform.OS === 'android') {
    text = text.replace(/\r?\n/g, '').replace(/[\u0080-\uFFFF]/g, ''); 
    // If android, remove unwanted chars. 
  }
  return text;
}).then(response => JSON.parse(response));

选项 2:

fetch('https://example.com/login', {
    method: 'POST',
    body: JSON.stringify({
        username: Uname,
        password: Upass
    })
}).then((response) => response.text()).then((responseJson) => {
    alert(JSON.stringify(responseJson));
    console.log(JSON.stringify(responseJson));
}).catch((error) => {
    alert(JSON.stringify(error));
    console.log(error);
})

推荐阅读