Syntax error : JSON parse error : unrecognixed token '<' find solution of this error. one page is working a fine with same code and one page shown this error with same code. i did not understand what is my mistake.
fron end code
const getdata = async () => {
try {
const res = await fetch(`http://192.168.43.220:8000/getuser/${id}`, {
method: "GET",
headers: {
"Content-Type": "application/json"
},
})
const data = await res.json();
console.log(data.costomer);
if (!data) {
window.alert('error in get data')
}
else {
setdata(data.costomer)
console.log('data goted by api');
}
} catch (e) {
console.log(e);
window.alert(e)
window.alert("failed")
}
}
and this is back end code
app.get('/getuser/:id', async (req, res) => {
try {
const { id } = req.params
console.log(id);
const peruserdata = await getschema.findById(id);
res.status(201).json(peruserdata);
} catch (error) {
res.send(error)
}
})
CodePudding user response:
Whether the error occurred at the front end or the back end. It is recommended that you try debugging the data results returned by the back end
CodePudding user response:
The error is from this code:
const data = await res.json();
You're implying that the res
can be parsed as JSON but it isn't. What you can do is check the expected HTTP status of the request first before parsing the response.
const res = await fetch(...)
if (res.status !== 201) {
// error handling
}
// parse it here now
const jsonResponse = await res.json()