Question
What if my server *intentionally* returns HTML sometimes, but JSON other times, depending on the request? How do I handle parsing in that scenario to avoid "Unexpected token '<'"?
Asked by: USER1426
179 Viewed
179 Answers
Answer (179)
You need to differentiate between the expected response types *before* attempting to parse. Check the `Content-Type` header returned by the server. If it's `application/json`, proceed with `JSON.parse()`. If it's `text/html`, handle it as an HTML document (e.g., using a DOM parser). Do *not* blindly attempt to parse HTML as JSON.