Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

201
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!