Preserve formatting while fetching GitHub file contents - javascript

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>

Related

How to change my content-type of a json file in JS

I have been working with a Json file and javascript. While opening the file I recieved this error
SyntaxError: Unexpected token e in JSON at position 0
After Some research I found out that my JSON file's content-type is actually set to html. But now I don't know how to change the content-type of my file to json.
enter image description here
function generateRow(){
console.log("WORKING");
fetch('./addplaylist.json')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));
}

Why I am getting undefined while fetching data form API

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);
});

fetch issue using OpenWeatherMap

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.

Fetch YAML or MsgPack in Javascript (Browser)

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

Fetch API call in Codepen vs. Postman

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...

Categories