0
0
JavascriptDebug / FixBeginner · 4 min read

How to Handle Response in Fetch in JavaScript Correctly

To handle a response in fetch in JavaScript, use response.json() or response.text() to read the body, and always return or await this promise. For example, use fetch(url).then(response => response.json()).then(data => console.log(data)) to get JSON data.
🔍

Why This Happens

When you use fetch, the response body is a stream that needs to be read asynchronously. If you try to use the response directly without reading it, you get unexpected results or errors.

Many beginners forget to call response.json() or response.text(), which returns a promise that resolves to the actual data.

javascript
fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {
    console.log(response); // This logs the response object, not the data
    return response;
  })
  .then(data => {
    console.log(data); // This is still the response object, not the JSON data
  });
Output
Response {type: "cors", url: "https://jsonplaceholder.typicode.com/posts/1", redirected: false, status: 200, ok: true, ...} Response {type: "cors", url: "https://jsonplaceholder.typicode.com/posts/1", redirected: false, status: 200, ok: true, ...}
🔧

The Fix

You must call response.json() (or response.text() for plain text) to read the response body. This method returns a promise, so you need to return or await it to get the actual data.

This way, the next then receives the parsed data, not the response object.

javascript
fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json())
  .then(data => {
    console.log(data); // This logs the actual JSON data
  })
  .catch(error => {
    console.error('Error:', error);
  });
Output
{ userId: 1, id: 1, title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", body: "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto" }
🛡️

Prevention

Always remember that fetch returns a response object, not the data itself. You must explicitly read the body using response.json(), response.text(), or other methods depending on the content type.

Use async/await syntax for cleaner code and easier error handling.

Also, handle errors with catch or try/catch blocks to avoid silent failures.

javascript
async function getData() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Fetch error:', error);
  }
}

getData();
Output
{ userId: 1, id: 1, title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", body: "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto" }
⚠️

Related Errors

Common related errors include:

  • TypeError: Failed to fetch - Usually a network or CORS issue.
  • SyntaxError: Unexpected token - Happens if you try to parse non-JSON data with response.json().
  • Unhandled Promise Rejection - Occurs if you forget to add catch for errors.

Fix these by checking network, content type, and adding proper error handling.

Key Takeaways

Always call response.json() or response.text() to read fetch response data.
Use async/await or return promises properly to handle asynchronous response reading.
Add error handling with catch or try/catch to manage fetch failures.
Check response.ok to handle HTTP errors before reading the body.
Remember fetch returns a response object, not the actual data.