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

时间:2019-12-30 02:04:31

标签: react-native express

   signIn = () => { 
    //post data to express backend
    fetch('http://......./api/v1/auth', {
        method: 'POST',
        header: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
              body: `login=${this.state.login}&password=${this.state.password}`
    })

    .then((response) => response.json())
    .then((res) => {

      if (res.success === true) {
          this.props.navigation.navigate('Authorized')
      } else {
          alert(res)
      }
    })
    .done();
}

使用localhost:3000时,我不断收到此类错误以及网络失败错误

1 个答案:

答案 0 :(得分:1)

添加try catch。似乎响应是text/html格式。

signIn = () => { 
//post data to express backend
fetch('http://......./api/v1/auth', {
    method: 'POST',
    header: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
          body: `login=${this.state.login}&password=${this.state.password}`
})

.then(async (response) => {
  let res;
  try {
    res = await response.clone().json();
  } catch (e) {
    res = await response.text();
  }
  return res;
})
.then((res) => {

  if (res.success === true) {
      this.props.navigation.navigate('Authorized')
  } else {
      alert(res)
  }
})
.done();

}