【问题标题】:JSON Parse error: Unrecognized token '<' parse - React NativeJSON解析错误:无法识别的令牌'<'解析 - React Native
【发布时间】:2025-12-29 20:45:06
【问题描述】:

“JSON 解析错误:无法识别的令牌'

点击 API 时出现错误。 (响应采用 JSON 格式。)我正在尝试构建登录表单,但无法从数据库服务器检索用户数据。

constructor(){
super()
    this.state={
         email:'',
         password:'',
    }
}
handleLoginUser(){
            fetch('https://"mygoogleclouddatabaseip"/users/login', {
                    method: 'POST',
                    headers: {
                      Accept: 'application/json',
                      'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(this.state)})
                    .then(response => {
                        console.log(response);
                        return response.json();})
                    .then(responseData => {
                         console.log(responseData);
                         let result = JSON.parse(responseData);
                         return result;})
                    .then(data => {
                        if (result.success){
                            alert("Login successful");
                        }
                        else
                            alert("Unable to Login");
                    })
               }
}

【问题讨论】:

  • 检查服务器的响应。听起来服务器可能正在返回 HTML 或其他一些非 JSON 响应。
  • "响应是 JSON 格式" — 也许应该是这样,但错误消息另有说明。
  • response.json() let result = JSON.parse(responseData);?真的吗?你确定要这样做吗?

标签: javascript reactjs react-native


【解决方案1】:

问题是您的 response 不是有效的 json,并且在尝试执行 response.json() 时会出现错误。

请调试它并处理 response 不是有效 json 的情况。

或者其他问题可以在这里

let result = JSON.parse(responseData);

如果responseData 已经是一个javascript 对象,使用JSON.parse 会给你一个错误,如果response.json() 工作,这意味着JSON.parse 不是必需的并且给你错误。

你可能会问

为什么不需要JSON.parse

因为response.json() 将响应转换为javascript 对象,而JSON.parse 也这样做。

正确的方法是使用response.json() 而不是JSON.parse(仅当响应是有效的 json 时)。

【讨论】:

  • 我做了你的建议,但现在它给出了“网络请求失败”错误