I have a dotnet API function look like:
[HttpPost("searchbook")]
public IActionResult SearchBook([FromForm]bookquery query)
{
if (webservice.haserror()) {
return BadRequest("There have some error")
}
return webservice.data()
}
In the javascript, I have write fetch just like
function handleErrors(response) {
if (!response.ok) {
response.text()
.then(text => { throw new Error(text) });
}
return response;
}
function fetchdata() {
try {
fetch(url, {
method: "POST",
body: postData
})
.then(handleErrors)
.then(response => response.text())
.then(result=> dosomething())
.catch(error => console.log(`Error from api message : ${error}`))
}
catch (error) {
console.log(`Error in fetch : ${error}`)
}
but I have a problem which I can't get the error message : There have some error and which want put it to console.log but it show :
1. Error from api message : TypeError: Failed to execute 'text' on 'Response': body stream already read
2. Uncaught (in promise) Error: Generate Report Report with reason : record not find
In the past, I do it by ajax function, like this and it work :
$.ajax({
url: url,
type: "POST",
data: formData,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function (result, status, xhr) {
dosomething();
},
error: function (xhr, status, error) {
console.log(`Error from api message : ${xhr.responseText}`)
}
})
so can I know to do it in fetch ? Thank you