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);
}
}
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.
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?".
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).
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!