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 '<'"?

Responsive Ad Header

Question

Grade: Education Subject: Support
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:
179 Viewed 179 Answers

Answer (179)

Best Answer
(331)
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.