【问题标题】:How to fix SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON如何修复语法错误:意外的标记 \'<\', \"<!DOCTYPE \"... 不是有效的 JSON
【发布时间】:2023-02-03 20:43:19
【问题描述】:

所以我是 React Native 的新手,我正在尝试将数据从我的应用程序发送到我的后端并在我的后端控制台上播放该数据。

问题:我不断收到此错误:

SyntaxError: 意外的标记 '<', "<!DOCTYPE "... 不是有效的 JSON。

到处看看如何解决这个问题,没有任何效果......

这是从我的前端发送数据的部分的样子:

<View style={styles.container}>
  <TouchableOpacity onPress={ () => {

fetch(API_URL+'/get', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'multipart/form-data',
},
body:JSON.stringify({
  'name': 'item name',
  'description': 'item description',
})
})
.then((response) => response.json())
.then((responseJson) => {
  console.log(responseJson);
  this.setState({
      data: responseJson
   })
})
.catch((error) => {
  console.error(error);
})}

  } style={styles.Button}>
    <Text style={styles.ButtonText}>3abez</Text>
  </TouchableOpacity>
  </View>

我期待在我的控制台上看到: {'名称':'项目名称'}

【问题讨论】:

  • API 端可能存在错误,这意味着 API 正在返回 HTML 错误页面而不是实际数据。要查看错误,请在开发人员工具网络窗格中找到请求,选择它,单击预览选项卡并观察内容。

标签: node.js react-native fetch


【解决方案1】:

看起来服务器正在返回 HTML 而不是 JSON。这就是您收到“意外标记‘<’”错误的原因,因为 HTML 不是有效的 JSON。

  • 要解决此问题,您需要检查服务器发回的内容 并确保它返回一个 JSON 对象。如果未设置服务器 正确设置,您需要更正它。
  • 此外,确保您发送的 API 端点 请求是正确的,它是设置为接收的端点 并处理 POST 请求。
  • 您还可以检查响应标头和状态代码 服务器的响应以查看是否返回任何错误。

下面是一个工作代码示例,用于将数据从 React Native 应用程序发送到后端并在控制台中显示响应数据:

import React, {Component} from 'react';
import {View, TouchableOpacity, Text} from 'react-native';

const API_URL = 'http://your-backend-endpoint.com';

class App extends Componenenter code heret {
  constructor(props) {`enter code here`
    super(props);
    this.state = {
      data: {},
    };
  }

  handlePress = () => {
    fetch(API_URL + '/get', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        name: 'item name',
        description: 'item description',
      }),
    })
      .then(response => response.json())
      .then(responseJson => {
        console.log(responseJson);
        this.setState({
          data: responseJson,
        });
      })
      .catch(error => {
        console.error(error);
      });
  };

  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity onPress={this.handlePress} style={styles.button}>
          <Text style={styles.buttonText}>Send Data</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = {
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  button: {
    backgroundColor: '#ddd',
    padding: 10,
    borderRadius: 5,
  },
  buttonText: {
    fontSize: 18,
    color: 'black',
  },
};

export default App;

【讨论】:

    猜你喜欢
    • 2023-02-22
    • 2022-12-29
    • 2019-10-06
    • 2015-05-28
    • 2019-12-04
    • 2023-01-18
    • 2013-09-04
    • 1970-01-01
    相关资源
    最近更新 更多