How can I prevent the "SyntaxError: Unexpected token '<'" error from happening in the first place when consuming an API?

Responsive Ad Header

Question

Grade: Education Subject: Support
How can I prevent the "SyntaxError: Unexpected token '<'" error from happening in the first place when consuming an API?
Asked by:
120 Viewed 120 Answers

Answer (120)

Best Answer
(363)
Ensure that your API request is correctly configured to request JSON data. Set the `Accept` header to `application/json` in your request headers. This tells the server that you prefer a JSON response. Additionally, ensure that the server-side code is designed to always return valid JSON, even when errors occur (e.g., return a JSON object with an `error` field).