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

Ana*_*sad 6 react-native

“ JSON解析错误:无法识别的令牌'<'”按下api时显示错误。注意:响应为JSON格式。

fetch("http:/example.com", {method: "POST",
  body: JSON.stringify(
    {
      uname: uname,
      password: password      
    }
  )
})
.then((response) => response.json())
.then((responseData) => {
  AlertIOS.alert(
      "POST Response",
      "Response Body -> " + JSON.stringify(responseData.body)
  )
}).done();
       this.props.navigation.navigate("Home")
   };
Run Code Online (Sandbox Code Playgroud)

请帮忙。谢谢,

isp*_*ett 8

这意味着您从服务器收到的HTML响应可能是404或500错误。代替response.json()使用,response.text()您将获得文本中的html。

fetch("http:/example.com", {method: "POST",
  body: JSON.stringify(
    {
      uname: uname,
      password: password      
    }
  )
})
.then((response) => response.text())
.then((responseData) => {
  AlertIOS.alert(
      "POST Response",
      "Response Body -> " + responseData
  )
}).done();
       this.props.navigation.navigate("Home")
   };
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以尝试将标题添加到您的 fetch api,因为它会将您的记录发布到您的 url。

var dataObj = {}
dataObj.uname = uname,
dataObj.password = password

fetch("http:/example.com", {
  method: 'post',
  headers: {
    'Accept': 'application/json, text/plain, */*',  // It can be used to overcome cors errors
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(dataObj)
})
.then((response) => response.json())
.then((responseData) => {
  AlertIOS.alert(
      "POST Response",
      "Response Body -> " + JSON.stringify(responseData.body)
  )
}).done();
    this.props.navigation.navigate("Home")
};
Run Code Online (Sandbox Code Playgroud)


Ana*_*sad 2

最后下面的代码起作用了。问题出在 Body 参数上。

fetch("http:/example.com", {method: "POST",
  body: "uname=value1&password=value2" // <-- Post parameters        
})
.then((responseData) => {
  AlertIOS.alert(
      "POST Response",
      "Response Body -> " + JSON.stringify(responseData.body)
  )
}).done();
       this.props.navigation.navigate("Home")
};
Run Code Online (Sandbox Code Playgroud)