Parse API responce with javascript - 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

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;

Logging HTTP errors with Fetch API in node.js

I am trying to find the best way to log bad requests using node-fetch. Here is the code I came up with.
let response = fetch(url)
.then((response) => {
if(!response.ok)
{
//get error json from request and throw exception
}
return response.json();
})
.then((json) => {
return json.data;
})
.catch((error) => console.log(error));
The problem here is that response.json() returns a promise so I can't use that to extract the error message and construct an exception. I am pretty new to JS so I feel that the solution to this is very straight-forward and it's just going over my head! Could you guys help me out?
I typically do something like this:
fetch(...).then(
response=>{
if (response.ok){
return response.json()
}
else {
return response.json().then(i=>Promise.reject(i))
}
}
)
If you have access to await it becomes even simpler:
let response = await fetch(...);
if (!response.ok){
throw await response.json()
}
else {
return await response.json()
}

retrieving json data by a key

const username = 'merMan';
fetch("./datz.json")
.then(response => response.text())
.then((response) => {
console.log(response);
})
my data response looks like below, still having a difficult time simply getting a user specific data. My response data outputs like below. I have tried using find, but always returns find is not a function, response[username] does not work either.
[{"mermAn":{"baseMapId":"459cc334740944d38580455a0a777a24","customBaseMap":"","zoomn":"5","orient":"0","centLon":"-93.69999999999843","centLat":"38.64999999999935"},
{"catWoman":{"baseMapId":"459cc334740944d38580455a0a777a24","customBaseMap":"","zoomn":"5","orient":"0","centLon":"-93.69999999999843","centLat":"38.64999999999935"},
{"Riddler":{"baseMapId":"459cc334740944d38580455a0a777a24","customBaseMap":"","zoomn":"5","orient":"0","centLon":"-93.69999999999843","centLat":"38.64999999999935"}}]
You need to parse the response after response.text(), like:
fetch("./datz.json")
.then(response => response.text())
.then((response) => {
try {
const parsedArray = JSON.parse(response);
console.log(parsedArray);
} catch (error) {
// response could not be parsed
}
})
Use .json() instead of .text()
const username = 'merMan';
fetch("./datz.json")
.then(response => response.json())
.then((users) => {
console.log(users.find(x => typeof x[username] !== "undefined"));
})

Fetch res.json() Attempt to invoke intergace method 'java.lang.String...'

I'm trying to convert a response from fetch function into json format but when I do so I get an error Attempt to invoke interface method 'java.lang.string com.facebook.react.bridge.ReadableMap.getString(java.lang.String)' on a null object reference.
Here is my code snippet with fetch function:
export const fetchAllUsers = () => {
fetch('http://192.168.1.103:3000/api/userData')
.then(res => {
res.json();
//console.warn('res keys = ' + Object.keys(res))
})
}
If comment back the row with console.warn I see the following "res keys = type, status, ok, statusText, headers, url, _bodyInit, _bodyBlod, bodyUsed".
bodyUsed = false
status = 200
type = default
Why I can't convert a response into json format? Or is there any another way to do so?
UPDATE
I've added the second then but I still get the error and the console.warn('res is json') is not running:
export const fetchAllUsers = () => {
fetch('http://192.168.1.103:3000/api/userData')
.then(res => {
res.json();
//console.warn('res keys = ' + Object.keys(res));
})
.then(res => {
console.warn('res is json');
console.warn(res);
})
}
UPDATE_2
I've run fetch function with another url but still got the problem. It seems like .json() causes the error. When I'm trying to console the result of fetch in the first .then() I get json object with type, status etc keys.
export const fetchAllUsers = () => {
fetch(`http://${localIP}:${port}/api/userData`)
//.then(res => res.json())
.then(json => console.warn('JSON: ' + json))
.catch(e => console.warn('ERROR: ' + e))
}
UPDATE_3
Forgot to mention that I'm creating an Android app with React Native. For testing I'm using a physical smartphone. Chrome version there is 73.0.3683.
I've replaced my fetch query with the following:
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json));
But still get the same error.
When I run it in https://jsfiddle.net/ it works. So the reason is hidden inside the code execution on a smartphone.
There must be more context to your problem; see the below snippet. This clearly works.
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json));

Fetch error (evaluating 'input.bodyUsed')

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 .

Categories

Resources