How to Fix 'Unexpected token < in JSON at position 0' in JavaScript

If you are working with APIs and JavaScript, encountering the error "Uncaught SyntaxError: Unexpected token < in JSON at position 0" can be incredibly frustrating. This error typically occurs when your code expects a JSON object but receives something else—usually HTML code—instead.

This guide will walk you through the reasons why this happens and provide step-by-step solutions to fix it.

1. Understand Why the Error Occurs

The error message literally means that the JSON.parse() method (or the .json() method in the Fetch API) encountered a '<' character where it expected a curly brace or bracket. In web development, the character '<' is almost always the start of an HTML tag, such as <!DOCTYPE html> or <html>. This happens because your API request failed and returned an error page (like a 404 or 500 page) in HTML format instead of the JSON data you requested.

2. Check the Network Tab in Developer Tools

Before changing your code, you need to see exactly what the server is sending back. Right-click on your web page and select Inspect, then navigate to the Network tab. Refresh the page and look for the specific API request that is failing. Click on the request and look at the Response sub-tab. If you see HTML code here instead of JSON, you have found the source of the problem.

3. Verify the API Endpoint URL

The most common cause of a 404 error (which returns an HTML "Not Found" page) is a typo in the URL. Check your fetch() or axios call to ensure the path is correct. Ensure that:

  • There are no extra slashes (e.g., //api/data instead of /api/data).
  • You are using the correct protocol (http vs https).
  • The domain and port are specified correctly.

4. Set the Correct Request Headers

Sometimes the server doesn't know you want JSON unless you explicitly ask for it. You should include the Accept and Content-Type headers in your request. Update your Fetch code as follows:

fetch('your-api-url', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}

})

5. Handle Non-JSON Responses Gracefully

To prevent your app from crashing when this error occurs, you should always check the response status before attempting to parse the JSON. Use this standard pattern in your JavaScript:

fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok, received HTML instead');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

6. Check for Server-Side Redirects

If you are using a framework like React, Vue, or Blogger, and you are trying to fetch a local file that doesn't exist, the server might redirect you to the index.html page. This is common in Single Page Applications (SPAs). Ensure the file path to your local .json file is relative to the public directory and not just the source folder.

Conclusion

The "Unexpected token <" error is a signal that your JavaScript is trying to read HTML as data. By inspecting the Network Tab and ensuring your API paths and headers are correct, you can quickly resolve this issue and ensure your application handles data exchange smoothly.


💡 Pro Tip: Keep your software updated to avoid these issues in the future.


Category: #Website