0

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)
}

})
3
  • 3
    that error usually indicates that the server is replying with HTML - check the browser developer tools to see exactly what the server is sending in the response Commented Sep 9, 2022 at 2:50
  • or change the data variable to const data = await res.text(); and then you can see what is returned. Commented Sep 9, 2022 at 3:53
  • Does this answer your question? JSON Parse error: Unrecognized token'<' - react-native Commented Sep 9, 2022 at 4:23

2 Answers 2

0

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

Sign up to request clarification or add additional context in comments.

1 Comment

This looks like a comment and not an answer. If you have a question for the original poster, you should leave a comment in the question's thread instead of submitting an answer. Answers should be submitted when you feel you can reasonably solve the original poster's question.
0

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.