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
Related
One can fetch the contents of a file in a GitHub repository using the code below.
fetch("https://raw.githubusercontent.com/Ayanmullick/test/master/AutomationAcc/test1.ps1")
.then(response => response.text())
.then(data => document.write(data))
However, the formatting gets lost. I faced the same problem with the api too.
fetch("https://api.github.com/repos/Ayanmullick/test/git/blobs/97e69f38b60f360dc8a22e07c6c395feb0e004a8")
.then(response => response.json())
.then(data => atob(data.content))
.then(decoded =>document.write(decoded))
Is there a way to preserve the formatting while fetching the file contents?
The issue isn't that fetch() is loosing your formatting, it is that document.write() won't write whitespace. You can see this by console.log()ing instead:
fetch("https://raw.githubusercontent.com/Ayanmullick/test/master/AutomationAcc/test1.ps1")
.then(response => response.text())
.then(data => console.log(data))
If you need to write it to the DOM, try using a <pre> tag that preserves whitespace exactly:
fetch("https://raw.githubusercontent.com/Ayanmullick/test/master/AutomationAcc/test1.ps1")
.then(response => response.text())
.then(data => document.getElementById('code').textContent = data)
<pre id="code"></pre>
I am a beginner and I am learning JavaScript. I am trying to make some projects with API. I am using Unsplash API to fetch some data. But I am getting typeerror. In my JavaScript code, lines 4 to 7, I am trying to console.log the likes, views, and downloads but they are showing undefined.
fetch(`https://api.unsplash.com/photos/random/?client_id=YILDy9SO8bXBp_dwX7aFO3R_UAs1-8v0gTrK2o2wllE&count=1`)
.then(response => response.json())
.then(data => {
console.log(data);
console.log("Likes:", data.likes);
console.log("Views:", data.views);
console.log("Downloads:", data.downloads);
});
What is the problem? How can I get those values?
The data object returns in an array, so you have to get the 0th element to then access the object and its data. Like this:
fetch(`https://api.unsplash.com/photos/random/?client_id=YILDy9SO8bXBp_dwX7aFO3R_UAs1-8v0gTrK2o2wllE&count=1`)
.then(response => response.json())
.then(data => {
console.log(data);
console.log("Likes:", data[0].likes);
console.log("Views:", data[0].views);
console.log("Downloads:", data[0].downloads);
});
when we use fetch in JS to issue a get request, we normally do thing like this
fetch(endpoint).then(res => res.json()).then(result => ...)
However I was watching Wes Bos's JS 30 courses and he called the intermediate result that the fetch returns a blob as in
fetch(endpoint).then(blob => blob.json()).then(result => ...)
I found the definition for blob here https://developer.mozilla.org/en-US/docs/Web/API/Blob
I am not knowledgable enough to judge if Wes Bos was using the right term here to refer to it as blob and I have no ways to contact him directly and ask him. Hope I can find some answers here.
fetch returns a Response object, not a Blob - if you try to use blob methods like .slice and .stream on the result, errors will be thrown, since those methods do not exist.
// Not OK:
fetch('data:,Hello%2C%20World!').then(blob => blob.slice()).catch((err) => console.log('err', err.message));
// OK:
fetch('data:,Hello%2C%20World!').then(res => res.text()).then(console.log);
Note that the Response can be converted into a Blob, but the return value from fetch would still be a Response:
fetch(endpoint)
.then(response => response.blob())
.then((blob) => {
// work with the blob here
});
Calling the response a blob is incorrect. They're somewhat similar, but not the same. Better to avoid calling it a blob to avoid confusion.
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...
I am new to redux and reactjs and I am trying to fetch some server side data to my code.
This is my thunk fetch:
fetch(`/WebApp/Dashboard/CreateAlert`).then(response => {
console.log(response);
});
This is what I see in the console:
In fiddler I see the response is "Success" as expected.
Is this response valid and how do I parse it, I am a bit confused and there is very little info online.
EDIT:
I changed to:
fetch(url).
then(response => response.json())
.then(json => {
console.log(json);
});
And I received the object. Now when I send a complex type(List), I see the bellow:
If you want to parse a json response:
fetch(`/WebApp/Dashboard/CreateAlert`)
.then(response => response.json())
.then(json => {
console.log(json);
});
See https://developer.mozilla.org/en-US/docs/Web/API/Body for all of the methods you can use to parse the response body.