I am trying to use the d3.json method to access JSON Data from an endpoint. I am able to successfully access the data using the fetch method below, however I am not sure how to change this to the d3.json method. How can I pass the argument "credentials:include"
fetch('http://0.0.0.0:example.com',{
credentials: 'include'
})
.then(response => response.json())
.then( json => console.log(json))
My attempt would be something like this, however I am not sure where I would add the credentials argument.
d3.json('http://0.0.0.0:example.com', json => console.log(json))
d3.json use fetch so the same will work
From the doc:
d3.json:
Fetches the JSON file at the specified input URL. If init is specified, it is passed along to the underlying call to fetch; see RequestInit for allowed fields.
d3.json('http://0.0.0.0:example.com', {credentials: "include"}, function(error, json) {
console.log(json);
})
Related
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.
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))
Take a simple API fetch call, such as follows:
fetch('https://api.nasa.gov/planetary/apod?api_key=xxxxxxxxx')
.then(res => res.json())
.then(data =>setPic(data.hdurl))
I'm still a bit confused about how this works. My understanding is this - information is sent from the web server as JSON, but to displayed on a web page it has to be converted into a normal JS object. Is this correct?
And if so, how does the above method convert JSON to a JS object? Because as I understand it, res.json simply extracts the JSON, it doesn't convert it.
[...] how does the above method convert JSON to a JS Object? Because
as I understand it, res.json() simply extracts the JSON, it doesn't
convert it.
This is what .json() does - it resolves the JSON string and parses it into a JS Object:
// Retrieves data from a URL
fetch('data:text/plain;charset=utf-8,%7B%22myJSON%22%3A%20%22myJSON%22%7D')
// Resolve the data retrieved from the URL as JSON and parse into a JS Object
.then(res => res.json())
// Work with the resolved data
.then(data => {
console.log('data has been resolved as: ' + typeof data);
console.log(data);
});
If you want the JSON String to remain a JSON String, you can use .text() instead:
// Retrieves data from a URL
fetch('data:text/plain;charset=utf-8,%7B%22myJSON%22%3A%20%22myJSON%22%7D')
// Resolve the data retrieved from the URL as a string
.then(res => res.text())
// Work with the resolved data
.then(data => {
console.log('data has been resolved as: ' + typeof data);
console.log(data);
});
I'm developing a web app where I need to update the configuration of a certain type of graph. To do so, I'm using Python3 with flask and html.
I want to update the configuration dynamically, which means that I don't want to use the function render_template and instead, I want to use return jsonify(message) .
Below I included the function that I want to use to update the data. This function is used as a callback on the rest of my system and those prints are being executed well, which means that on the flask side, everything seems to be okay. However, I don't know what I should put on the html side to receive this data.
Here is the code that I'm using in flask to send the data:
#app.route('/online_visualization_update')
def online_visualization_update(msg):
print("I should change the network.")
print("The message was ", msg)
with app.app_context():
return jsonify(msg.transition, msg.marking)
This is the code I tried to implement on html to receive the data sent by flask:
<script type=text/javascript>
fetch('/online_visualization_update')
.then(response => response.json())
.then(data => console.log(data))
.catch((error) => {console.error('Error:', error);
});
</script>
Currently, this is not working because the the fetch is being performed every time I open the webapp. What am I doing wrong?
Ideally, I would like to have a function on javascript that is executed only when it receives the data from flask but I don't know whether fetch works like that or not.
Thank you
For that you need to use Fetch API in javascript like this
// write function like this
function callApi(){
fetch('/online_visualization_update')
.then(response => response.json())
.then(data => console.log(data))
.catch((error) => {
console.error('Error:', error);
});
}
Refer this for more about fetch:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Add this code in your Html page:
<Div class="container">
<button type="button" onclick="callApi()">Call func</button>
<!--you need to call function like this whenever you need data -->
</Div>
how to parse json from an url into html by using javascript (programmatically) and i facing an problem with this ?
api: https://corona.ps/API/summary
You need to use the built in JavaScript fetch() method which returns a promise. Use .then() to handle the response and .catch() to handle any errors relating to the fetch call.
Here's an example function using your api link:
function getData () {
fetch("https://corona.ps/API/summary")
.then(res => res.json())
.then(data => console.log(data)) // will log js object
.catch(err => console.log(err))
}