Fetch error (evaluating 'input.bodyUsed') - javascript

In the code below, I don't get the response and get an undefined error instead.
fetchData() {
fetch(Global.user_list)
.then((response) => {
if (response.ok) {
return response.json()
}
})
.then((data) => {})
.catch((err)=> {
alert(err)
})
}

I got the same exception by chance. I was doing a refactoring and failed to provide a valid url to the fetch function.
So I would recommend you check what is inside Global.user_list .

Related

'Uncaught TypeError: Cannot read properties of undefined (reading 'then')' on API request

My page brake when i make an request to an API, i receive the contents and it prints on the console.
function getFilms() {
fetch('https://ghibliapi.herokuapp.com/films')
.then((response) => response.json())
.then((data) => {
console.log(data);
return data;
});
}
export default getFilms;
I've tried to use a implicit return and return outside of the '.them' without success.
I was receiving undefined because the the caller didn't received the return of the API. Solved by returing the fetch.
function getFilms() {
return fetch('https://ghibliapi.herokuapp.com/films')
.then((response) => response.json())
.then((data) => {
console.log(data);
});
}
export default getFilms;

Within a fetch() Promise, how to .catch server errors messages when status is 4xx or 5xx? [duplicate]

This question already has answers here:
fetch: Reject promise with JSON error object
(5 answers)
Closed last year.
In a locally run Node.js script, this works when status is 200:
// module file
import fetch from "node-fetch";
export const getJSON = () => {
const url = 'https://api.somesite.com/api/v0/etc';
const options = {method: 'GET', headers: {Accept: 'application/json'}};
const request = fetch(url, options)
.then(response => response.json())
.catch(err => console.log("somesite:", err));
return Promise.resolve(request);
};
// execution file
import { getJSON } from './libs/api_requests.mjs';
console.log("func call", await getJSON());
But the fetch also works without triggering the .catch logic when the response status is 4xx or 5xx (see for example this answer).
Execution doesn't break and I actually receive an error message when the function is called as if that would be the correct, normal result - as the output of response.json().
This message is in plain English, something like "error: 'Incorrect path. Please check https://www.somesite.com/api/'".
I would like to preserve/display this error message, only I would like to catch it within the function getJSON in the module file, instead of having to wrap some logic around it at the destination, potentially repeating the same code multiple times everywhere the function is called, instead of dealing with the issue just once at the source.
So I modified the .then clause like this, which also works:
.then(response => { if (response.ok) { // .ok should be status 200 only, I suppose
return response.json();
} else { throw new Error(response.status) }
This now triggers the .catch clause as intended, displaying "Error: 404 [etc]". Except what I would like to throw is the original error message "Incorrect path [etc]" and that I could not do. I tried
.then(response => { if (response.ok) {
return response.json();
} else { throw new Error(response.json()) } // somesite: Error: [object Promise]
.then(response => { if (response.ok) {
return response.json()
} else { throw new Error(Promise.resolve(response.json())) } // somesite: Error: [object Promise]
.then(response => { if (response.ok) {
return response.json()
} else { throw new Error(return response.json()) } // SyntaxError: Unexpected token 'return'
.then(response => { if (response.ok) {
return response.json();
} else { throw new Error(Promise.resolve(request)) } // somesite: Error: [object Promise]
I guess I need to resolve the response.json() promise as if all was ok, but how to do that?
I also had a look at the request object with console.dir(request, { depth: null }) to see if I could extract the error message from there, but I couldn't find it and the object still contained many unexpanded elements like [Function: onerror] or [Function: onclose] for example.
Try response.text() instead of response.json() when the status code is 400 or 500.
In my experience, the error messages are typically returned by the text callback.
See this answer to a similar question.
Edit:
Added the following code, suggested by OP.
.then((response) => {
if (response.ok) {
return response.json();
}
else {
return response.text()
.then((text) => {
throw(text);
// if the error is an object and you just want to display some elements:
throw(JSON.parse(text));
});
}
})
.catch((err) => {
// in case you want to log the error
console.log("somesite: ", err));
return new Error("somesite: " + err);
});

Parse API responce with javascript

I have got the response from the JSON API, but I don't know how to parse it, it just comes back with an error, I don't know enough about it to figure it out, it returns:
(node:36308) UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token o in JSON at position 1
var fetch = require('node-fetch');
fetch('https://sv443.net/jokeapi/v2/joke/Any', function(res){
if (res.ok) {
return res;
} else {
console.log(res.statusText);
}
})
.then(res => res.json())
.then((json) => {
var parsedData = JSON.parse(json)
console.log(parsedData.joke);
});
You just need to do the following to access the delivery.
fetch("https://sv443.net/jokeapi/v2/joke/Any?type=single")
.then(response => {
return response.json();
})
.then(json => {
// likely to be json.delivery but cannot
// confirm until rate limits have been lifted
console.log(JSON.stringify(json));
})
.catch(err => {
console.log(err);
});
Try this:
fetch('https://sv443.net/jokeapi/v2/joke/Any', function(res){
if (res.ok) {
return res;
} else {
console.log(res.statusText);
}
})
.then(response => response.json())
.then(data => console.log(data));
You are already parsing it with res.json(). It returns an object (in promise) which can be accessed directly. Depending on a type prop you may have different props to check for. For example twopart joke will have setup: question, and delivery: answer

How to retrieve axios data from the promise

I am currently trying to query my backend using axios and to that specific address I am sending with res.json an object and I am also able to see it with postaman. But when trying to build a function to retrieve it, my object looks like:Promise {pending}. How can i refactor my function ?
isAuthenticated = () => {
return axios.get('https://myaddress/authenticate')
.then(function (response) {
return response.data
})
};
You need to call the promise like so:
isAuthenticated().then(result => console.log(result))
.catch(error => console.log(error));
Use This code and let me know if still, you face a problem.
const isAuthenticated = () => {
return axios.get('https://myaddress/authenticate').then(response => {
// returning the data here allows the caller to get it through another .then(...)
return response.data
}).catch(error => console.log(error));
};
isAuthenticated().then(data => {
response.json({ message: 'Request received!', data })
})
here is similar questions as yours: Returning data from Axios API || Please check it as well.

Catch() not handling 404

I'm making a script to fetch some data from my api:
const success = (response) => {
console.log(response);
};
const failed = (error) => {
console.log(error);
};
axios.$http.get('/somedata')
.then((response) => {
success(response.data);
})
.catch((error) => {
failed(error);
});
/somepage is a non-existing page so it returns a 404. But the catch is not handling this. Why not? In my console I have the error TypeError: Cannot read property 'data' of undefined. Why does it not run the failed() function? I don't understand.
Found out it was related to a custom interceptor handling 401-errors (but not 404 errors)...
Judging by the error message, it looks like "success(response.data);" is being called. Is it possible the server is successfully returning a page that says something like "Error 404" rather than actually returning http response code 404?
You could impliment a check for 404s.
axios.$http.get('/somedata')
.then(response => {
if(response.status !== 404) //or any status code really
success(response.data);
else
failed(response)
})
.catch((error) => {
failed(error);
});
Then again what you probably want to check for is to make sure it's a 200 that returns.
axios.$http.get('/somedata')
.then(response => {
if(response.status === 200)
success(response.data);
else
failed(response)
})
.catch((error) => {
failed(error);
});

Categories

Resources