【问题标题】:SyntaxError: Unexpected token e in JSON at position 2SyntaxError:位置 2 处 JSON 中的意外标记 e
【发布时间】:2020-10-07 22:26:46
【问题描述】:

我正在研究 React 并使用 Spring Boot 制作的 POST API。 这是代码

async postData() {
  console.log(JSON.stringify(this.state));
  try {
    const results = await fetch("/student", {
      crossDomain: true,
      method: "POST",
      headers: {
        "Content-type": "application/json",
      },
      body: JSON.stringify(this.state),
    });

    const data = await results.json();
    console.log("data", data);
    //this.props.history.push("/Resume");

    this.setState({
      owner: "",
      student_field_interest1: "",
      student_field_interest2: "",
      firstname: "",
      lastname: "",
      contactno: 0,
      address: "",
      gender: "",
    });
  } catch (err) {
    console.log(err);
  }
}

在访问 API 之前 我正在发送这个 JSON 对象

{"data":[],"owner":"5eeaac70f21e4c2b3a35a8c0","student_field_interest1":"ML","student_field_interest2":"DL","firstname":"Pushkar","lastname":"Jain","contactno":"09991736000","address":"Room no 106 Oxford Caps Upes Road","gender":"Male"}

在击球时 我收到此错误

SyntaxError: JSON 中第 2 位的意外标记 e

【问题讨论】:

  • 服务器返回什么?听起来它不是有效的 JSON。
  • 你能发布console.log的输出吗?
  • 可能是服务器端的错误,有错误可以查看springboot控制台吗?

标签: javascript json reactjs spring-boot post


【解决方案1】:

您检查 API 响应了吗?我在本地环境中尝试并且工作正常 结果消息是一个错误,但这是故意的,这是预期的结果。

【讨论】:

    【解决方案2】:

    您的 this.state 没有有效的 json。请从以下 url 验证您的 JSON https://www.jsonschemavalidator.net/

    Post 不适用于无效的 json

    【讨论】:

      猜你喜欢
      • 2016-08-29
      • 2020-07-02
      • 2021-05-06
      • 1970-01-01
      • 2019-10-31
      • 1970-01-01
      • 2017-12-24
      • 1970-01-01
      • 2017-07-29
      相关资源
      最近更新 更多