Search code examples
javascriptnode.jsfetch

nodejs - check if fetch response is json or text


I'm new to coding and i'm using node-fetch and trying to check if the response is a json or text but i get an error if the response is text.

If the response is a json it will work fine but if the response is text i get an error.

The error i get:

invalid json response body at https://url.com/api reason: Unexpected token i in JSON at position 6

My code:

const fetch = require("node-fetch");

const doFetch = async (url) => {
  try {
    let res = await fetch(url);

    try {
      return res.json();
    } catch (error) {
      return res.text();
    }
    
  } catch (error) {
    console.log('fetch error', error.message);
  }
}

Solution

  • You could check what is the content type from the header:

    const contentType = response.headers.get("content-type");
    

    if it's "application/json" then use the json() method. else if it's "text/plain", use the text() method.