【问题标题】:Post request with ReactJS使用 ReactJS 发布请求
【发布时间】:2020-04-07 00:28:49
【问题描述】:

我目前正在尝试在 React 中为我的应用发出 POST 请求。在我的应用程序的先前版本中,我使用 AJAX 对此端点 URL 进行了发布请求。在原版中工作得很好,在 Postman 中工作。 (我可以填写 :psid 的键值并进行发布)

https://endpoint.com/viewquestion/:psid

但是,当我转换到 React 并使用 fetch 方法时,它一直抛出这个错误:

SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data"

谁能帮我解决这个问题?谢谢!

原始代码(Jquery):

function ViewQuestion(psid) {
  $.ajax({
    url:
      "https://endpoint.com/viewquestion/" +
      psid,
    dataType: "text",
    type: "post",
    contentType: "application/x-www-form-urlencoded",
    data: $(this).serialize(),
    success: function(data, textStatus, jQxhr) {
      console.log(data);
      // Logger(data);
    },
    error: function(jqXhr, textStatus, errorThrown) {
      console.log(errorThrown);
    }
  });
}

新代码(反应):

viewQuestion: (ps_id) => {
  fetch(
    `https://endpoint.com/viewquestion/${ps_id}`,
    {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
    }
  )
    .then((res) => res.json())
    .then((data) => {
      console.log(data);
    })
    .catch((error) => {
      console.log(error);
    });
}

【问题讨论】:

  • 您没有发送任何数据,请尝试将data: JSON.stringify({psid: ps_id}) 添加到您的提取选项中
  • 这不是真正的 React 问题,更多的是 fetch 问题。但是从这两个函数来看,看起来你还没有完成 fetch 调用。您没有发送任何数据,因此您的应用程序可能返回错误而不是 json。
  • 谢谢,我已经添加了行,但仍然出现同样的错误。

标签: reactjs post fetch


【解决方案1】:

这可能是您从服务器获得的响应。在您的原始代码中,您没有执行response.json(),现在您执行了。尝试删除它并 console.log 响应以查看您得到了什么以及如何访问该数据。

【讨论】:

  • 您好,感谢您的回复,但由于某种原因它似乎仍然无法正常工作...与以前相同的错误
  • @ChunkyLow 我们可以看到您作为响应发回的数据吗?尝试删除 res.json() 并尝试 console.log(res) 并删除另一个 .then() 只是为了测试。将结果添加到您的帖子中,这将非常有帮助。
  • 谢谢,现在可以使用了!看来这确实是 res.json() 搞砸的结果
  • @ChunkyLow 酷!我已经更新了答案,因此您可以将其标记为解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-17
  • 2020-12-31
  • 1970-01-01
  • 1970-01-01
  • 2013-07-15
  • 2015-02-16
  • 2013-02-22
相关资源
最近更新 更多