Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 39 ยท Beyond Fetch

Debugging Network Requests

Debug AJAX problems fast: read the DevTools Network panel, inspect headers and payloads, diagnose CORS, 404, mixed content and Content-Type errors, and test with fakes.

When an AJAX feature fails, the page usually tells you very little: a spinner that never stops, an empty list, or a vague "Something went wrong". The real story is in the network traffic between the browser and the server. Learning to read that traffic turns hours of guessing into a few minutes of looking. Almost every problem falls into a short list of causes, and each leaves recognizable fingerprints.

This lesson shows how to use the browser's Network panel, how to read a request and a response, how to diagnose the failures you will meet most often and how to add your own logging and test doubles so that bugs are easy to reproduce. The DevTools parts are read-only (they depend on your browser, not on the sandbox), while the logging and testing techniques run live.

Open the Network panel

Every major browser has developer tools: press F12, or Ctrl+Shift+I (Cmd+Option+I on macOS), and choose the Network tab. Recording starts when the panel is open, so open it before you trigger the request, or reload the page. Useful controls:

  • Filter by type. Click Fetch/XHR to hide images, scripts and styles and see only AJAX calls.
  • Preserve log. Tick it to keep requests across page navigations, which matters when a form submit reloads the page and you want to see what happened.
  • Disable cache. While DevTools is open, this forces fresh responses, so you can tell a caching problem from a real bug.
  • Throttling. Simulate "Slow 4G" or "Offline" to see how your loading and error states behave.
  • Search (Ctrl+F in the panel). Finds text in any request or response.
  • Copy as fetch / cURL. Right-click a request to copy it as a runnable command. Replaying a failing request in a terminal tells you whether the problem is in the server or in your page.

The request list has columns for name, status, type, size and time. A red row is a failed request: either an HTTP error status or a failure that never produced a status. Click a row to open its details.

Anatomy of a request in the panel

The detail view has tabs. Their names vary slightly between browsers, but the information is the same.

Tab What to check
Headers The final URL, method, status code, request headers (what you sent, including Content-Type, Authorization, cookies) and response headers (Content-Type, Access-Control-*, Cache-Control, Set-Cookie)
Payload The query string and the request body, shown as sent. Compare it with what the API documentation expects
Preview / Response The body: Response shows the raw text, Preview a formatted tree for JSON
Timing Where time went: waiting for the server (TTFB), downloading, queuing
Initiator Which line of your code started the request
flowchart TD
  A["Request failed or<br/>result looks wrong"] --> B{"Does the request<br/>appear in the Network panel?"}
  B -->|"No"| C["Your code never called fetch:<br/>check events, conditions, console errors"]
  B -->|"Yes, red with no status"| D["Network-level failure:<br/>CORS, DNS, offline, mixed content, blocked"]
  B -->|"Yes, has a status"| E{"Status code?"}
  E -->|"4xx"| F["Wrong URL, method, auth<br/>or data: read Payload and Response"]
  E -->|"5xx"| G["Server bug: read the<br/>response body and server logs"]
  E -->|"2xx"| H["Check Content-Type and body<br/>against what your code expects"]

Start by asking whether the request exists at all, then follow the branch.

Reading status codes at a glance

The status tells you which side to blame (see HTTP for AJAX developers):

  • 400, 422: the server rejected your data. Open Payload and Response; the body usually names the field.
  • 401: not authenticated: a missing or expired token, or a cookie that was not sent.
  • 403: authenticated but not allowed, or a CSRF token problem.
  • 404: wrong URL (a typo, a missing /api prefix, a trailing-slash difference) or the resource really does not exist. Compare the Request URL with the documentation character by character.
  • 405: the route exists but not for this method; you sent GET to a POST-only endpoint.
  • 429: you are being rate limited; see retries and backoff.
  • 500, 502, 503, 504: the server or a proxy in front of it failed. Your request may be fine.
  • 200 with an error in the body: some APIs wrongly wrap errors in a success status. Your code must check the body as well.

The failures you will meet most

CORS errors

The console prints a message such as "blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present". In the Network panel the request may show a status but your code gets a TypeError, or the row is red with no readable response. The browser sent the request, and the server may even have processed it, but the browser refuses to give the response to your page. Check the response headers for Access-Control-Allow-Origin. If the request was a preflight (an OPTIONS request before your real one, triggered by custom headers or methods like PUT), look at that row: the server must answer it with a 2xx status and the right Access-Control-Allow-* headers. You fix CORS on the server, not in the front end. If you cannot change the API, call it through your own server (see AJAX security and headers and CORS). Also confirm the URL: a redirect to a different origin, or a server error page without CORS headers, can look like a CORS problem when the real issue is a 500.

Mixed content

A page served over https:// may not load http:// resources. Browsers block mixed-content AJAX requests, and the console says so. The fix is to use https:// for the API (or a relative URL such as /api/users, which always follows the page's scheme).

Wrong Content-Type

Two variants cause confusing bugs. In the first, you send JSON without Content-Type: application/json; many servers then see an empty or unparsed body and report missing fields. Compare the request headers and Payload tab with what the server expects. In the second, the server answers with HTML (a login page, a 404 error page, a framework debug page) while your code calls response.json() and fails with SyntaxError: Unexpected token '<'. That error message always means "the body started with <, so it was HTML, not JSON". Open the Response tab to see the real page, then check the URL and whether you were redirected to a login page.

Cache and stale data

If an old value keeps appearing, look at the Size column: "(disk cache)" or "(memory cache)" means the browser did not ask the server. Check the response Cache-Control and ETag headers (see caching and polling), and test with Disable cache ticked.

Cookies and credentials

A 401 on a request you expected to be authenticated often means the cookie was not sent. For cross-origin requests you need credentials: "include" on the client and Access-Control-Allow-Credentials: true plus a specific origin (not *) on the server. The Headers tab shows whether a Cookie header went out, and DevTools marks cookies that were blocked by SameSite rules.

Race conditions and duplicates

If results flicker or an old answer overwrites a new one, look at the Timing and order of requests: two similar requests with the slow one finishing last is the signature of a race (see cancelling requests). Two identical requests firing at once usually means an event handler was registered twice or a button was not disabled.

Diagnose in code: the failure you cannot see

Network-level failures reveal very little to JavaScript on purpose: a TypeError from fetch() could be offline, DNS failure, CORS or mixed content, and the browser hides which one for security reasons. The console and Network panel know more than your code does. What your code can do is capture everything it can see and log it consistently. This helper wraps fetch() in a function that records the method, URL, timing, status and content type, and diagnoses the typical "HTML instead of JSON" mistake. It runs here against constructed responses instead of a real server.

JS A logging wrapper that diagnoses responses

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Reading the body as text first, then parsing it, is a small habit that pays off: when JSON.parse fails, you still have the text to show in the log, whereas response.json() throws and consumes the body.

Use the browser's own tools too. console.table() prints arrays of objects as tables, console.group() groups related lines, console.time("name") with console.timeEnd("name") measures duration and the Console's Preserve log option keeps messages across reloads. In the Sources panel, a breakpoint (click a line number) or debugger; statement pauses your code with all variables visible, and XHR/fetch breakpoints pause the code when a request URL matches a text you enter. Remove debugger statements before shipping.

Test doubles: reproduce problems on demand

Real servers are hard to make fail on cue. A test double replaces fetch with a function that returns responses you control: success, 404, 500, a slow answer, invalid JSON or a network failure. This makes bugs reproducible and lets you write automated tests of your loading and error handling without any server. The trick that makes it easy is to let the code under test receive the fetch function as a parameter (with the real fetch as the default value), so tests can pass a fake.

JS Testing error handling with a fake fetch

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The same idea scales up. Libraries such as Mock Service Worker intercept requests at the network layer, and test runners offer their own fake functions and fake timers; Node's built-in test runner can replace globalThis.fetch with a mock. Whichever tool you pick, the principle is identical: one place to decide what the "server" answers, with failures included.

A debugging routine that works

  1. Reproduce it, with the Network panel open and Preserve log on.
  2. Find the request. If it is missing, the bug is in your code (check the console for errors first).
  3. Read the URL, method and status. Many bugs end here: a typo, a wrong method or a 401.
  4. Compare Payload and headers with the documentation. Is the body what the server expects? Is Content-Type right?
  5. Read the real response body, not only the status. Servers often explain what is wrong.
  6. Replay it outside the browser (copy as cURL). If it works there, the issue is browser-specific: CORS, cookies or cache.
  7. Write a fake that reproduces the failure, fix the code and keep the test.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Your code logs SyntaxError: Unexpected token '<' after calling response.json(). What does this almost always mean?

    HTML starts with <. Typical causes are a wrong URL (a 404 page), a redirect to a login page or a server error page.
  2. 2. A red row in the Network panel has no status code and the console mentions CORS. Where is the problem fixed?

    CORS is the server's permission for the browser. no-cors only gives you an unreadable opaque response.
  3. 3. Why read the body with response.text() and then JSON.parse() while debugging?

    If response.json() fails, the body has already been consumed. With text() you still have the text to inspect.
  4. 4. What is the benefit of passing the fetch function into the code under test as a parameter?

    A replaceable dependency lets you reproduce any server behavior without a server.
  5. 5. A page served over https tries to call http://api.example.com. What happens?

    Browsers block insecure subrequests from secure pages. Use https for the API or a relative URL.

Summary

  • Open the Network panel before the request; filter to Fetch/XHR, preserve the log and use Disable cache and throttling when needed.
  • Read the Headers, Payload, Response and Timing tabs; the status code tells you which side to suspect.
  • Learn the fingerprints: CORS (red row, console message), mixed content, wrong Content-Type, HTML where JSON was expected, stale cache, missing cookies, races.
  • In code, log method, URL, status, content type and timing, and read the body as text first so failures keep their evidence.
  • Use test doubles for fetch to reproduce successes and failures on demand, and keep them as tests.

Next: Project: User Directory puts the whole track to work in a small application.