Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

202
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda