首页 > 解决方案 > JSON Parse error: Unrecognized token '<' - React Native

问题描述

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

I am continuously receiving such error and also network failed error when using localhost:3000

标签: react-nativeexpress

解决方案


添加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();

}


推荐阅读