Sometime you API backend could not respect the contract, and send plain text (ie. Proxy error: Could not proxy request ...
, or <html><body>NOT FOUND</body></html>
).
In this case, you will need to handle both cases: 1) a valid json response error, or 2) text payload as fallback (when response payload is not a valid json).
I would suggest this to handle both cases:
// parse response as json, or else as txt
static consumeResponseBodyAs(response, jsonConsumer, txtConsumer) {
(async () => {
var responseString = await response.text();
try{
if (responseString && typeof responseString === "string"){
var responseParsed = JSON.parse(responseString);
if (Api.debug) {
console.log("RESPONSE(Json)", responseParsed);
}
return jsonConsumer(responseParsed);
}
} catch(error) {
// text is not a valid json so we will consume as text
}
if (Api.debug) {
console.log("RESPONSE(Txt)", responseString);
}
return txtConsumer(responseString);
})();
}
then it become more easy to tune the rest handler:
class Api {
static debug = true;
static contribute(entryToAdd) {
return new Promise((resolve, reject) => {
fetch('/api/contributions',
{ method: 'POST',
headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify(entryToAdd) })
.catch(reject);
.then(response => Api.consumeResponseBodyAs(response,
(json) => {
if (!response.ok) {
// valid json: reject will use error.details or error.message or http status
reject((json && json.details) || (json && json.message) || response.status);
} else {
resolve(json);
}
},
(txt) => reject(txt)// not json: reject with text payload
)
);
});
}
localhost
. So I changed thefetch('http://localhost/img/fr.json')
. Further I was running my app on localhost:8080, so a CORS issue occurred which was taken care by disabling it via a chrome plugin. Anyway thanks a lot @jcubic for giving a heads up, because sometimes it not any fault in the code.https://api.com/search?q=chicken&app_id=${APP_ID}&app_key=${APP_KEY}
) to await fetch(http://localhost:3000/https://api.com/search?q=chicken&app_id=${APP_ID}&app_key=${APP_KEY}
), but I am still getting an error saying "Unexpected token < in JSON at position 0". Even I have turned ON my Moesif Orign & CORS Changer. What should I do now.