我在尝试从 Fetch API 检索 JSON 响应时遇到上述错误。由于某种原因,它适用于 4 个 API 中的 2 个,但不适用于其余 2 个。我没有看到前端代码在检索响应方面有任何差异。请查看下面的代码:
我不确定这里有什么问题:
async handleSubmit(event) {
event.preventDefault();
let responseArray = [];
const token = localStorage.getItem("token");
let url = "https://api_sports/api/developSports/?";
var form = new FormData();
form.append("destIds", this.state.destID);
form.append("destInfo", this.state.infoID);
form.append("destPostal", this.state.postID);
// Figure out the way to append the data in form
await fetch(url, {
method: "POST",
body: form,
headers: { "Authorization": `Token ${token}` },
"mimeType": "multipart/form-data",
}).then((results) => {
return results.json()
}).then(response => {
console.log("Actual Response: ", response)
if (response.status === 204) {
console.log("Response 204: ", response)
this.setState({ alertMessage: "Success" })
}
else if (response.status === "error") {
console.log("Expected Error : ", response);
responseArray.push(response.messages);
this.setState({
alertMessage: "IPError",
rangeArray: responseArray[0]
});
}
})
.catch(err => {
console.log("Error ", err);
})
}
谢谢!
请检查一次 API 响应,因为您的 API 没有返回 JSON 对象,这就是您收到此错误的原因。它可能是一个格式错误的 JSON 响应。
我可以通过添加以下代码来解决此问题,将响应分为两部分(HTTP 和 JSON)
await fetch(url, {
method: "POST",
body: form,
headers: { "Authorization": `Token ${token}` },
"mimeType": "multipart/form-data",
}).then((results) => {
if (results.status === 204) {
this.setState({ alertMessage: "Success" })
}
else {
return results.json()
.then(response => {
if (response.status === "error") {
responseArray.push(response.messages);
this.setState({
alertMessage: "Failure",
rangeArray: responseArray[0]
});
}
});
}
})
谢谢大家!