Common causes
- The API URL is wrong, so the server answers with its HTML 404 page. Check for a missing
/apiprefix, a typo or a wrong port. - In a single-page app, the dev server or host returns
index.htmlfor every unknown path, so a wrong API path gets the app's HTML with status 200. - The server crashed and returned an HTML error page (500, 502, 504) from the app, a proxy or a CDN.
- The session expired and the server redirected to an HTML login page.
- A relative URL like
fetch("api/users")resolves against the current page path. Use/api/users.
See what the server actually sent
Read the body as text first and log it. The first lines of the HTML usually say what went wrong:
const response = await fetch("/api/users");
const text = await response.text();
console.log(response.status, response.headers.get("content-type"), text.slice(0, 300));Handle it properly in fetch
Check the status and the content type before calling response.json(), so you get a clear error instead of a parse error:
async function getJson(url, options) {
const response = await fetch(url, options);
const type = response.headers.get("content-type") ?? "";
if (!response.ok) {
throw new Error(`Request failed with ${response.status}`);
}
if (!type.includes("application/json")) {
const preview = (await response.text()).slice(0, 100);
throw new Error(`Expected JSON but got ${type || "no content type"}: ${preview}`);
}
return response.json();
}Frequently asked questions
Why does it work locally but fail in production?
The API base URL or a proxy rule usually differs. In development a proxy forwards /api to the backend; in production the same path may hit the static host, which returns index.html.
What if the unexpected token is 'u' or 'o'?
"undefined" is not valid JSON means you passed undefined to JSON.parse, and "[object Object]" is not valid JSON means you passed an object that was already parsed. Don't call JSON.parse on the result of response.json().
Is this a CORS problem?
No. A CORS failure gives a network error and you can't read the body at all. If you can see HTML, the request reached a server that answered with HTML.