I've tried all sorts of ways to get weather data from open weather
if I paste this into the browser I get data
http://api.openweathermap.org/data/2.5/weather?q=London&appid=6e93b3d15872f914c6929fed9ea71e9a
but if I use it with fetch or Axios or various other methods that work for me with other API's I get nothing back. Can anyone tell me what I am doing wrong? thanks
index.html
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
</body>
<script>
fetch('http://api.openweathermap.org/data/2.5/weather?q=London&appid=6e93b3d15872f914c6929fed9ea71e9a')
.then(data => data.json())
.then(data => {
console.log(data);
})
</script>
</html>
Use https instead of http. You will get data.
This is the correct format:
https://api.openweathermap.org/data/2.5/weather?q="+cityName+"&units=metric&apikey="+key
change http to https
Try this
const response = await fetch("http://api.openweathermap.org/data/2.5/weather?q=London&appid=6e93b3d15872f914c6929fed9ea71e9a");
const data = await response.json();
console.log(data);
Also wrap you code inside try/catch to catch any possible errors.
You can also use promises instead of async/await -
fetch("http://api.openweathermap.org/data/2.5/weather?q=London&appid=6e93b3d15872f914c6929fed9ea71e9a")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => {
console.log(error);
});
Also it will be better if you provide solutions that you have already tried in the question.
Related
Sorry if this was posted a lot, I read through several articles but could not find the solution. So, I'm fetching a large JSON from this API, and I would like to cache the response somehow in the localStorage, so the next time the page loads, the scripts first checks if there is an object with the requested ID inside the JSON, and renders the content if there is one - and if there isn't, goes of to the API to fetch it.
I was thinking of setting up two fetch() functions, and this is what I have:
fetch(url + id)
.then((response) => {
localStorage.setItem('myResponse', response);
})
.catch((error) => {
console.log(error);
})
Then, check if there is something saved inside the localStorage, and if it is good, use it to render the HTML, if not, go on to another fetch to get it from the API.
if(localStorage) {
createHTML(localStorage.myResponse);
} else {
fetch(url + id)
.then(response => response.json())
.then(data => createHTML(data))
}
But, in the first fetch, if I use JSON.stringify(response), it just shows it as an empty object, so it the localStorage it looks like: myResponse - {}. If I do console.log(response.json()); on the first fetch, it shows PromiseĀ {<pending>}.
I've tried to make something out of that, but without results...any help much appreciated!
response.json() is a Promise, it needs to be either awaited, or chained a .then(); If you simply log it as is, all you'll get is Promise {<pending>} because it hasn't resolved yet.
fetch(url + id)
.then( response => response.json() )
.then( json => {
localStorage.setItem('myResponse', JSON.stringify(json));
})
Or with the async/await syntax :
const response = await fetch(url + id);
const json = await response.json();
localStorage.setItem('myResponse', JSON.stringify(json));
I know how to fetch JSON with the Fetch API like this:
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));
I tried to replicate the same thing to get MsgPack or YAML data, but all my attempts have failed. I obviously know how to deserialize data, but I suspect I feel a bit lost with chained promises which I don't fully grasp. Since there is no response.yaml(), I need to us an extra step but I can't make it work. I tried with response.body() and response.blob(). Each time I do it, no data is available at the time of the console log. Which I assume means that my data is still a promise instead of being processed and called with the callback.
I have tried things like:
fetch('http://example.com/movies.json')
.then(response => response.body())
.then(data => console.log(deserialize(data)));
or:
fetch('http://example.com/movies.json')
.then(response => response.body())
.then(raw => deserialize(raw))
.then(data => console.log(data));
Here deserialize is a placeholder for the deserialize/decode function for either format.
Anybody has an example using YAML (I suspect more popular than MsgPack).
Maybe this npm package can help you with parsing yaml data: https://www.npmjs.com/package/js-yaml, https://github.com/nodeca/js-yaml.
example.yaml:
docker:
- image: ubuntu:14.04
- image: mongo:2.6.8
command: [mongod, --smallfiles]
- image: postgres:9.4.1
This works for me:
fetch('/example.yaml')
.then(res => res.blob())
.then(blob => blob.text())
.then(yamlAsString => {
console.log('yaml res:', yamlAsString)
})
.catch(err => console.log('yaml err:', err))
First we convert the result to a Blob. After that we call the text() method on it which converts the blob to a string.
https://developer.mozilla.org/en-US/docs/Web/API/Blob/text
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))
}
I'm attempting to collect some data from the Last.fm API. Using Postman, and with the call below, I am getting a response.
http://ws.audioscrobbler.com/2.0/?method=geo.gettopartists&country=spain&api_key=4a9f5581a9cdf20a699f540ac52a95c9
When I try to achieve the same result on Codepen, I don't get a response. This is the code I'm using:
fetch("http://ws.audioscrobbler.com/2.0/?method=geo.gettopartists&country=spain&api_key=4a9f5581a9cdf20a699f540ac52a95c9")
.then(response => response.json())
.then(data => console.log(data))
What am I missing here?
As both of the commenters mentioned
CORS issue: you can append https://cors-anywhere.herokuapp.com/(hacky work around)
specify the data type to be json...
Try this it should work:
fetch('https://cors-anywhere.herokuapp.com/http://ws.audioscrobbler.com/2.0/?method=geo.gettopartists&country=spain&format=json&api_key=4a9f5581a9cdf20a699f540ac52a95c9')
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.log(err))
Note: You should not share that API key...