【发布时间】: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。
-
谢谢,我已经添加了行,但仍然出现同样的错误。