清除浏览数据后首次加载API出现JSON语法错误,刷新后消失求排查
Hey Claire, let's break down this issue and figure out what's going on!
Why This Error Happens
The Unexpected token < in JSON at position 0 error almost always means your API isn't returning valid JSON. Instead, it's sending HTML (like a login page, error message, or redirect response) — the < is the start of an HTML tag, which breaks the JSON parsing.
Since this only happens after clearing browsing data and on the first load, it's definitely tied to session/cookie behavior. Here's what's likely happening:
- When you clear data, you're deleting the session cookie your site uses.
- The first request to
api.phpdoesn't include this cookie, so your server's session logic fails and returns HTML instead of JSON. - On the second refresh, the browser has now received the session cookie from the first response, so the request works as expected.
Step 1: Verify the First Request's Response
First, let's confirm what the API is returning on that first failed load:
- Open your browser's DevTools (F12) and go to the Network tab.
- Clear your browsing data again, then refresh the page.
- Find the
api.php?action=showDoctorinforequest in the list, click it, and check the Response tab. You'll probably see HTML here (like a login form or error page) instead of JSON.
Step 2: Fix the PHP Session Initialization
Looking at your api.php code, you're checking $_SESSION['sessionOBJ'] but you might be missing a critical line: session_start().
In PHP, you must call session_start() before accessing or modifying $_SESSION. Without it, the session cookie won't be created or sent to the browser, and your server won't recognize the session on subsequent requests.
Update your api.php code to start the session first:
session_start(); // Add this line at the VERY TOP of api.php if(!isset($_SESSION['sessionOBJ'])) { $_SESSION['sessionOBJ'] = new doctorSession(); } // Rest of your API logic...
Step 3: Ensure the API Returns JSON Even on Errors
If your server encounters a session issue (like an unauthenticated user), it should return a JSON error response instead of HTML. For example:
// If session validation fails header('Content-Type: application/json'); http_response_code(401); echo json_encode(['error' => 'Unauthorized: Session not valid']); exit;
This way, your frontend won't try to parse HTML as JSON, and you can handle the error gracefully.
Step 4: Improve Frontend Error Handling
Your current fetch code doesn't handle cases where response.json() fails (like when the response is HTML). Add a catch for this scenario to debug and show better user feedback:
fetch(url, { method: 'GET', credentials: 'include' }) .then(function(response) { // ... your existing status checks ... // Add a catch for JSON parsing errors return response.json().catch(function(jsonError) { // Log the raw response to debug return response.text().then(function(rawResponse) { console.error('API returned non-JSON:', rawResponse); throw new Error('Invalid server response'); }); }); }) .then(function(data) { // ... your existing success logic ... }) .catch(function () { // ... your existing error handling ... });
Additional Checks
- Make sure your session cookie has the correct
SameSiteattribute (e.g.,SameSite=LaxorSameSite=Noneif cross-domain) to ensure it's sent with the request. - Verify that your server isn't redirecting unauthenticated requests to an HTML login page — this is a common culprit for this exact error.
Let me know if you find something unexpected in the network response, or if these fixes don't resolve the issue!
内容的提问来源于stack exchange,提问作者Claire

