How to fetch dynamic json with respond.json function using javascript [duplicate] - javascript

I am trying to use fetch api to bring back some data, however am unable to map it to the console once I have retrieved it.
fetch('http://jsonplaceholder.typicode.com/users', {
method: 'GET'
}).then(function(response) {
console.log(response)
response.forEach(i => console.log(i.name));
}).catch(function(err) {
console.log(`Error: ${err}` )
});
The error i get is
response.map is not a function
so I tried to parse the response,(ie var data=JSON.parse) which did not work, with the error
SyntaxError: Unexpected token o in JSON at position 1"
Interestingly, when doing the same thing with a XMLHttp request, I was required to parse it, so I would also be interested to know why the difference between these two methods of retrieving the data.
If anyone could point me in the right direction, I would be really grateful.

The Fetch API returns a response stream in the promise. The response stream is not JSON, so trying to call JSON.parse on it will fail. To correctly parse a JSON response, you'll need to use the response.json function. This returns a promise so you can continue the chain.
fetch('http://jsonplaceholder.typicode.com/users', {
method: 'GET'
})
.then(function(response) { return response.json(); })
.then(function(json) {
// use the json
});

Understanding promises is key to using the fetch API.
At the time you're trying to parse your response and loop through it, the response is actually just a promise. In order to utilize the contents of the actual response from the request, you'll have to do some promise chaining.
fetch('http://jsonplaceholder.typicode.com/users').then(function(response) {
// response.json() returns a promise, use the same .then syntax to work with the results
response.json().then(function(users){
// users is now our actual variable parsed from the json, so we can use it
users.forEach(function(user){
console.log(user.name)
});
});
}).catch(err => console.error(err));

It appears that you might be accessing the json incorrectly. You could try calling response.json() instead.
fetch('http://jsonplaceholder.typicode.com/users', {
method: 'GET'
}).then((response) => {
response.json().then((jsonResponse) => {
console.log(jsonResponse)
})
// assuming your json object is wrapped in an array
response.json().then(i => i.forEach(i => console.log(i.name)))
}).catch((err) => {
console.log(`Error: ${err}` )
});
This example is structured to match your example, but ideally, you would return response.json() on that first .then block and proceed on the next block. Here is a similar example that proceeds on the next block.
In your particular case, you can view the Fetch API as a json aware wrapper for "XMLHttpRequest"s. Main differences being that the Fetch API is simpler, functional-like, and has convenience methods. David Walsh does a reasonable comparison in his blog post, which I recommend you take a look at. Plain "XMLHttpRequest"s just pass you whatever string was sent back from the server, it has no idea it could be JSON, and thus leaves it to the user to parse the response whatever way they see fit.

Related

Modern way to consume a json based flask api with javascript

I'm new to web programming, I been learning the basics of Flask such as http requests, template inheritance, flask forms, saving data on the database etc.
I saw that some people only use flask as backend and its api its json based, and for the frontend they use React. Since I'm learning the basics of JavaScipt I don't want to use libraries like React or Jquery, I want to use just JavaScript. I was searcing and found that many people use AJAX with Jquery, or axios to consume an api. Is there any way to consume my flask api with just JavaScript without using any library or framework?
Is there any way to consume my flask api with just JavaScript without using any library or framework?
Yes, using fetch, which is built in to all modern browsers. A query for data transmitted in JSON format looks like this:
In a non-async function, if you are returning the result of the last call to then:
// Do the request
return fetch("/path/to/the/data", {/*...options if any...*/})
.then(response => {
// Check for HTTP success (`fetch` only rejects on *network* failure)
if (!response.ok) {
// HTTP error
throw new Error(`HTTP error ${response.status}`);
}
// Read the body of the response and parse it from JSON into objects and such
return response.json();
})
.then(data => {
// ...`data` has the data from the call, parsed and ready to go
});
...or if you aren't:
// Do the request
return fetch("/path/to/the/data", {/*...options if any...*/})
.then(response => {
// Check for HTTP success (`fetch` only rejects on *network* failure)
if (!response.ok) {
// HTTP error
throw new Error(`HTTP error ${response.status}`);
}
// Read the body of the response and parse it from JSON into objects and such
return response.json();
})
.then(data => {
// ...`data` has the data from the call, parsed and ready to go
})
.catch(error => {
// ...something went wrong, handle/report `error`...
});
fetch uses promises, so you'll want to read up on those.
In an async function, if you are allowing errors to propagate to the caller:
// Do the request
const response = await fetch("/path/to/the/data", {/*...options if any...*/});
// Check for HTTP success (`fetch` only rejects on *network* failure)
if (!response.ok) {
// HTTP error
throw new Error(`HTTP error ${response.status}`);
}
// Read the body of the response and parse it from JSON into objects and such
const data = await response.json();
// ...`data` has the data from the call, parsed and ready to go
or if you aren't:
try {
// Do the request
const response = await fetch("/path/to/the/data", {/*...options if any...*/});
// Check for HTTP success (`fetch` only rejects on *network* failure)
if (!response.ok) {
// HTTP error
throw new Error(`HTTP error ${response.status}`);
}
// Read the body of the response and parse it from JSON into objects and such
const data = await response.json();
// ...`data` has the data from the call, parsed and ready to go
} catch (error) {
// ...something went wrong, handle/report `error`...
}
More about async functions on MDN.

How can I return the response data from Auth0's API on my API?

I'm calling Auth0's API with axios to fetch a list of users. I'm trying to return them using the syntax that I'm using this syntax:
.then(res => {
console.log(res.data) // Prints the deired result
return res.status(200).json(res.data);
})
res.data is printing the desired result. But I'm getting and empty response body on Postman.
I also tried return res.data, only to get a timeout.
What am I missing?
You're calling the status method on the Axios response object when it should be called on the Express response object.
You should name the Auth0 API response something other than res to make sure res inside the callback refers to the Express response object. Or better use destructuring. And you don't have to set the 200 status code since it is set automatically.
.then(({ data }) => res.json(data))

fetch data from json running on node.js

I want to fetch data from JSON object which is on my localhost .
..This might be really stupid question but I am beginner in JS.
and is there any other way to fetch data ??
fetch('http://localhost:3000/show')
.then(result => {
console.log(result);
return result.json();
});
.then(data => {
console.log(data);
});
.catch(error => {
console.log(error);
});
this http://localhost:3000/show contains json objects.
it has retrieved data from mongoose.
Remove the semicolons between each .then call.
Promises use a kind of "monadic" pattern: each method on a promise returns another promise, which has the same API. This means you can chain promise methods indefinitely.
So:
fetch()
.then(/* stuff */)
.then(/* more stuff */)
.catch(/* even more stuff */); // <-- this is the only semicolon
The same is true of many Array methods, so you'll often see code like this:
Object.keys( someObj ) // returns an array
.map(/* iterator function */) // Array.map returns an array
.filter(/* iterator function */) // Array.filter returns an array
.sort(/* comparator function */); // Array.sort returns an array
Again, only one semicolon is needed, because each step of the statement produces an array, and JS lets you anticipate that.
If that doesn't help, you might want to post the error you're getting.
I should add that result.json() will throw if the server at http://localhost:3000/show fails to provide the HTTP header Content-Type: application/json. Even if the response body is entirely valid JSON, the HTTPResponse class refuses to do .json() if the server doesn't state that the content is json.
Also, if this code is running in a browser, and is served from a different host (or port), you will need to do CORS stuff. See https://stackoverflow.com/a/48287868/814463 for possible help.
If your endpoint '/show' returns the json data without any issue, then the below code should console you the json response.
fetch('http://localhost:3000/show')
.then(res => {
console.log(result);
return res.json()
)}
.then(json => console.log(json))
.catch(err => console.log(err));

How to get the response data from promise in React?

I am setting up a very basic react app, and trying to call my local host server (separate backend server), which has JSON data on it. I want to extract the data returned from the promise, but nothing I do seems to work. Here is my code:
fetch('http://localhost:8080/posts')
.then(function(response) {
const items = response.json()
console.log(items)
})
I have tried response.json(), response.body, I tried logging the body with .then(functio(body) { console.log(body)}), response.data, response.body, but nothing works. Here is what the console prints out:
How can I take the output it is giving me, and get it in an array that I can iterate through? The "content" and "id" are what I need access to.
and FYI, the array, when i go to localhost:8080/posts in my browser is simple:
[{"id":1,"content":"hello, this is post 1"}]
any help is appreciated, thanks!
The call toresponse.json()will also return a promise so you need too handle that also. Try the code below.
fetch('http://localhost:8080/posts')
.then(function(response){ return response.json(); })
.then(function(data) {
const items = data;
console.log(items)
})

Using fetch() Webapi

I am trying to see how browser's native webapi fetch() api works. So far I have this: Sample-Code and it works fine. But what I don't understand why is it streaming string which I have to convert to a JSON? I am not sure why would anybody even need to stream a JSON as string through a REST API? I am pretty sure I am missing something here but I am not sure how I should tell fetch() to get the response as JSON and not as a ReadableByteStream which I have to convert to a string and parse it for a JSON.
My Question is this,
Why is a string being streamed here?
How do I tell fetch() to fetch my response as text or json so that I can do response.json() or response.text() as mentioned in the docs? (FYI I tried adding a header object and creating a Header instance and passing it to fetch() neither changed my response.
All you need to do is call
fetch("https://api.github.com/users/ajainarayanan").then(res => res.json());
Here is some modified code the has the same result
fetch("https://api.github.com/users/ajainarayanan")
.then(res => res.json())
.then(res => console.log('Profile: ', JSON.stringify(res, null, 2)));
Apparently I have to do response.json() in one then handler and have the actual value in subsequent then handlers. Update-code. What I didn't realize was response.json() returned another Promise which I should handle like a promise. So console.log(response.json()) will naturally just console log a JSON object instead of my actual json. Thank your #aray12 for you answer. I didn't realize the answer until I realize .json() returned a promise.
PS: Adding this as an answer as I couldn't add this in comments.

Categories