Introduction: Understanding the “Unexpected token ‘<‘” Error
In modern web development, handling server responses is a crucial aspect of building interactive web applications. One of the most common issues developers face when dealing with AJAX requests, APIs, or fetching data from a server is the “Unexpected token ‘<‘” error. This error occurs when your code expects a response in JSON format but receives HTML instead.
Specifically, this issue arises when you attempt to parse HTML data as JSON. Typically, when the server sends an HTML page (for example, an error page or a redirect response), but the client expects a JSON response, the error message “Unexpected token ‘<‘” will be thrown. The <
character is the opening tag for HTML elements, and when JSON parsing is attempted, it can’t be processed correctly, triggering this error.
This comprehensive guide explores every facet of this error, including how it occurs, how to identify it, and most importantly, how to resolve it.
1. Understanding the Error: “Unexpected token ‘<‘”
The error message “Unexpected token ‘<‘” is seen when the JSON.parse()
function encounters a character that it doesn’t expect. The JSON.parse()
function is used to convert a JSON string into a JavaScript object, and it only understands a specific format that adheres to JSON standards. Here’s a typical scenario:
Example:
fetch('https://api.example.com/data')
.then(response => response.json()) // Parsing as JSON
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
If the server response is HTML instead of JSON, the .json()
method tries to parse HTML content, resulting in the “Unexpected token ‘<‘” error. The <
symbol, which is the start of an HTML tag, isn’t valid in JSON format and leads to this error.
2. Common Causes of the Error
2.1 Server Returns HTML Instead of JSON
A common cause of this error is when the server returns an HTML page instead of a JSON object. This could happen for several reasons, including:
- The server encountered an error and returned an error page (e.g., a 404 Not Found page or a 500 Internal Server Error page).
- A redirect response is returned (e.g., the server returns an HTML page to redirect to another URL).
- The requested resource is unavailable, and an HTML error page is returned instead.
In such cases, the response you receive may contain HTML content, which can start with a <
character (like <!DOCTYPE html>
or <html>
), which is not valid in JSON format.
2.2 Incorrect Headers or Content-Type
Another reason this error might occur is if the server sends a response with an incorrect Content-Type
header. If the server mistakenly sends a response with a text/html
content type, but the client expects application/json
, the .json()
method will fail when attempting to parse the HTML as JSON.
2.3 Misconfigured API or Endpoint
An incorrectly configured API or endpoint might return HTML instead of JSON. For example, a GET request might be directed to the wrong endpoint, causing the server to return an HTML error page instead of the expected JSON response.
2.4 Network Issues or Failures
Network issues such as server downtime or an unreachable API endpoint may also lead to receiving HTML error pages, which contain error messages, stack traces, and HTTP headers rather than JSON data.
2.5 Redirects Handling in AJAX Calls
When performing AJAX requests (via Fetch API or XMLHttpRequest), a redirect (e.g., 301 or 302) can cause the browser or client-side JavaScript to fetch an HTML page instead of the expected JSON response. If the response body contains an HTML redirect page, trying to parse it as JSON will result in the “Unexpected token ‘<‘” error.
3. How to Identify and Diagnose the Error
To fix the “Unexpected token ‘<‘” error, it is essential first to identify the root cause. Here are the steps to diagnose the issue:
3.1 Inspect the Response in the Browser Console
Most modern browsers (such as Chrome or Firefox) provide developer tools that allow you to inspect the network requests and responses. Here’s how you can use the browser developer tools to diagnose the error:
- Open the Developer Tools in your browser (usually accessible with the
F12
key or right-click → Inspect). - Go to the Network tab.
- Refresh the page or trigger the AJAX request that is causing the error.
- Look for the request in the Network tab. Click on the request and inspect the Response.
- Check the Response Body. If you see HTML content instead of JSON (e.g.,
<html>
,<body>
,<!DOCTYPE html>
), it indicates that the server is returning HTML instead of JSON.
3.2 Check the Response Headers
You can also inspect the Content-Type header of the response. The Content-Type
header tells the client what kind of data it should expect. For example:
- A valid JSON response should have the header
Content-Type: application/json
. - An HTML response will have the header
Content-Type: text/html
.
If the response has an incorrect Content-Type
, you may need to address the issue on the server-side configuration.
3.3 Check the API Response Status Code
Sometimes, the server may return a non-2xx status code (like 404, 500, etc.), and the body of the response may contain an HTML error page. You should check the HTTP status code as well:
- A 200 OK status with a valid JSON response is expected for a successful API call.
- A 404 Not Found or 500 Internal Server Error status indicates that something went wrong on the server side.
3.4 Check Server Logs
If you have access to server logs, you should inspect them for any issues that might have caused an HTML response instead of JSON. It might provide helpful information about routing problems, incorrect endpoints, or server misconfigurations.
4. Solutions to Resolve the “Unexpected token ‘<‘” Error
Once you’ve diagnosed the problem, you can implement a solution. Here are some possible solutions depending on the cause of the error:
4.1 Ensure the Server Returns JSON
If the server is returning HTML instead of JSON, the server-side code needs to be fixed. Here’s how:
- Check API endpoints: Ensure that the correct endpoint is being hit by the client and that the server is returning the appropriate JSON response.
- Return JSON from the server: If the server is supposed to return JSON, ensure the response is generated as JSON and set the
Content-Type: application/json
header. - Handle errors properly on the server: If an error occurs on the server (such as a 404 or 500 error), ensure that the response is still valid JSON (with an error message or status code), not HTML.
4.2 Handle Non-JSON Responses Gracefully
In some cases, you may want to handle non-JSON responses gracefully. For example, you can check the Content-Type
of the response before attempting to parse it as JSON.
Here’s an example using the Fetch API to check the Content-Type
header:
fetch('https://api.example.com/data')
.then(response => {
// Check if the response is JSON
if (response.headers.get('Content-Type').includes('application/json')) {
return response.json();
} else {
throw new Error('Expected JSON, but received HTML');
}
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
This approach prevents the error by verifying the content type before attempting to parse the response.
4.3 Handle Redirects Properly
If your AJAX requests are being redirected (for example, due to authentication or expired sessions), you might be getting an HTML redirect page instead of the expected JSON data. Here are some ways to handle redirects:
- Check for redirection status codes: Make sure that if a 3xx status code (such as 301 or 302) is returned, you follow the redirect properly.
- Configure CORS and credentials: If the redirect is due to authentication, ensure you handle cookies or tokens correctly with CORS (Cross-Origin Resource Sharing) and credentials.
4.4 Fixing Incorrect Headers
If the Content-Type
header is wrong, it’s a server-side issue. Make sure that your server is setting the correct Content-Type: application/json
header for JSON responses. For example, in Express.js:
res.setHeader('Content-Type', 'application/json');
res.json({ message: 'Success' });
4.5 Debug Network Issues
If the issue is related to network failure, ensure the server is reachable, and there are no issues with DNS, connectivity, or routing. You can use tools like curl
or Postman
to check the API response outside of the browser and troubleshoot further.
The “Unexpected token ‘<‘” error typically happens when you attempt to parse HTML content as JSON. This usually occurs when the server sends an HTML response (such as an error page or redirect) instead of a JSON payload.
To resolve this issue, you should:
- Inspect the server response using the browser’s Developer Tools.
- Ensure that the server is sending JSON and set the correct
Content-Type
header. - Add error handling to gracefully handle unexpected HTML responses.
- Handle redirects and non-JSON responses by checking headers before parsing.
By following the steps above and carefully inspecting the network requests and responses, you can quickly diagnose and resolve the “Unexpected token ‘<‘” error, ensuring a smoother user experience and better data handling in your web applications.