I am getting above mentioned error on trying to retrieve the JSON response from Fetch API. For some reason it works with 2 API's out of 4, but not for the rest 2. I do not see any difference on Front end code in retrieving the response. Please have a look into below code:
I am not sure what's incorrect here:
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);
})
}
Thank you
Please check you API response once Because your API is not returning a JSON object that why you are getting this error. It may be a malformed JSON in response.
I was able to fix this issue by adding below code, splitting the response into two (HTTP and 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]
});
}
});
}
})
Thank you everyone
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.