Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

210
Vistas
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);
  }
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar

0

First of all: ask the right question

The error is thrown because you try to read the response content as JSON and apparently it is not a valid JSON-formatted string.

In this case, try to use the Response before asking to convert the content as JSON object. You should be able to read the response status code or print the raw content.

So the right question is not "How can I know I receive text or JSON?" because you are supposed to say to the server/API you request what you want.

The right question might be "If the response does not contain a valid JSON, what is it?".

My theory

I assumed you are sending a request to the https://url.com/api URL. The targeted endpoint might requires a parameter (a URL to shorten) which is missing.

If you print the raw content of the response you should see a message containing the word "invalid". It is the reason it says "Unexpected token i in JSON at position 6".

Personally I would use the response status code to determine if I received an error message (not in JSON) or the content I requested (in JSON).

Congrats!

You are new to coding and you already handled all kind of error a small piece of code in your application could throw. You are on good tracks. Keep it up!

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda