API call undefined - javascript

Hello guys im trying to use the API from HAPPi using axios, i get the data in the console but when i try to get the values i want, i get allways undefined (i also tried with vanilla and ajax but i get the same thing).
im newbie so i can't find out what im doing wrong.
axios .get("https://api.happi.dev/v1/music/artists?apikey=here_goes_the_api_key&page=1")
.then(response => {
console.log(response.data);
const artistName = response.data.result.artist;
const artistCover = response.data.result.cover;
const artistInfo = response.data.result.api_artist;
const artistAlbums = response.data.result.api_albums;
document.getElementsByClassName('artistName').innerText = artistName;
document.getElementsByClassName('artistCover').innerHtml = artistCover;
document.getElementsByClassName('artistInfo').innerHtml = artistInfo;
document.getElementsByClassName('artistAlbums').innerHtml = artistAlbums;
})
.catch(error => console.error(error));

you need to register at https://happi.dev/ using your email address and you will get an api-key which needs to be inserted in the api call url
https://api.happi.dev/v1/music/artists?apikey=your_key_here&page=1
like this, hopefully this will fix the issue you are facing and if you still face issue try using double quotes when calling below method.
document.getElementsByClassName("artistName").innerText = artistName;

ok i found the problem, i wasn't indexing the object like this:
const artistName = response.data.result[0].artist;
const artistCover = response.data.result[0].cover;
const artistInfo = response.data.result[0].api_artist;
const artistAlbums = response.data.result[0].api_albums;
thanks for all the help

Related

undefined error when fetching weather forecast api javascript

I am trying to fetch the weather forecast api json like I did with the current weather api, but it does not seem to work any way I try.
let inOneDay = {
fetchWeather: function(){
fetch("https://api.openweathermap.org/data/2.5/forecast?q=Dortmund&units=metric&cnt=1&appid=758fce6dd3722cf25cd213a13bbc5484"
).then(resp => resp.json())
.then(data => console.log(data));
}
};
I have no idea where I went wrong. I used the same logic to make the code below work:
let weather = {
fetchWeather: function(){
fetch("https://api.openweathermap.org/data/2.5/weather?q=Dortmund&units=metric&appid=758fce6dd3722cf25cd213a13bbc5484"
).then((response) => response.json())
.then((data) => this.displayWeather(data));
},
displayWeather: function(data){
const{icon,description} = data.weather[0];
const{temp} = data.main;
document.querySelector(".icon").src = "https://www.openweathermap.org/img/wn/" + icon + ".png";
document.querySelector(".celsius").innerText = Math.round(temp) + "°C";
document.querySelector(".desc").innerText = description;
}
}
Grateful for any ideas!
Examining the json reply from that API, it looks like the OP code expects different fields than the service provides.
const result =
{"cod":"200","message":0,"cnt":1,"list":[{"dt":1631577600,"main":{"temp":13.31,"feels_like":13.05,"temp_min":13.31,"temp_max":15.87,"pressure":1018,"sea_level":1018,"grnd_level":1007,"humidity":90,"temp_kf":-2.56},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04n"}],"clouds":{"all":95},"wind":{"speed":1.42,"deg":94,"gust":2.29},"visibility":10000,"pop":0,"sys":{"pod":"n"},"dt_txt":"2021-09-14 00:00:00"}],"city":{"id":2935517,"name":"Dortmund","coord":{"lat":51.5167,"lon":7.45},"country":"DE","population":588462,"timezone":7200,"sunrise":1631595820,"sunset":1631641686}};
const result0 = result.list[0]; // notice .list[0]
const weather0 = result0.weather[0]; // notice weather[0]
const main = result0.main; // notice main is a sibling prop to weather
const temp = main.temp
console.log(`weather is ${JSON.stringify(weather0)}`);
console.log(`main is ${JSON.stringify(main)}`);
console.log(`temp is ${temp}`);
Be sure to check for errors before dereferencing the result. It also looks like the api provides a cnt prop which might indicate the number of elements in the list.

Reusing variables later as integers/text later

I have tried getting cypress to save a text for later usage but I feel unable to reuse it as a variable
cy.get('.unrd').then(($span) => {
const filteredunread = $span.text()
cy.wrap(filteredunread).as('oldunreadmessage');
})
Codeblock to send a mail, wait and return to the inbox expecting an echo reply
cy.get('.unrd').then(($span) => {
cy.get('#oldunreadmessage') //seen as object
const newunread = $span.text()
expect(newunread).to.eq(cy.get('#oldunreadmessage') +1)
})
This gives me errors such as:
expected '(27)' to equal '[object Object]1'
I have tried to use .as(). However I seem to be unable to properly resolve my old object as a text or integer constant.
The first part is fine, but because of the cy.wrap you need to use should or then on the cy.get('#oldunreadmessage')
cy.get('.unrd').then(($span) => {
const newunread = $span.text();
cy.get('#oldunreadmessage').should('have.text', newunread);
})
or
cy.get('.unrd').then(($span) => {
const newunread = $span.text();
cy.get('#oldunreadmessage').then((oldunread) => {
expect(newunread)...
}
})

Discord.js snekfetch body undefined problem

const Discord = require("discord.js")
const snekfetch = require("snekfetch")
const client = new Discord.Client({disableEveryone: false});
//const CSGO = require("csgo-api"); // Import the npm package.
//const jb = new CSGO.Server('185.198.75.5', '27015') // Set the IP with port.
var prefix2 = "!"
client.on('ready', async ()=> {
snekfetch.get("http://query.li/api/csgo/185.198.75.5/27015").then(r => console.log(r.body.game.players.name));
//jb.getOnlinePlayers().then(data => console.log(data)) // Get & log the data
});
Hello friends, I'm trying to print the players section on http://query.li/api/csgo/185.198.75.5/27015 to message.channel.send but it gives undefined can you help me?
I'm using Google Translate sorry my English so bad :/
You are trying to get the body of the result. But it is null. Your result contains these children: game, whois, status, banner_url, and cached.
And also, your players are an array. So you should select an index to console.log().
Try this:
snekfetch.get("http://query.li/api/csgo/185.198.75.5/27015").then(r => console.log(r.game.players[0].name));
You can use this web site to beautify your response JSON.
EDIT:
If you want to print the names of all players then you can use a foreach() loop for players. Like this:
snekfetch.get("http://query.li/api/csgo/185.198.75.5/27015").then(r => {
r.game.players.forEach(player => {
console.log(player.name)
});
}
);

Extracting value from an object

I'm working on a discord bot, using discord.js.
I've been working on this command for too long without finding a solution, so I come here to ask for help.
Here is my problem, maybe it's really simple to solve to you, and that would be great :D
I want to create a command that sends a random gif, based on a keyword.
I'm using a node module called giphy-random.
(async () => {
const API_KEY = "hidden";
const gif = await giphyRandom(API_KEY, {
tag: "kawaii"
});
console.log(gif)
}
I would like to be able to get only the value 'url' of the const which is defined by the function (i'm maybe wrong in my words, I'm a beginner) in order to send it in a channel.
You simply want gif.data.url In fact if you change your console.log like this:
console.log(gif.data.url);
You'll see the url printed to the console.
According to the docs, the link is returned in data.url property of the resulting object. So your code should look like:
(async () => {
const API_KEY = "hidden";
const gif = await giphyRandom(API_KEY, {
tag: "kawaii"
});
console.log(gif.data.url)
}
You can simply access field like this:
const API_KEY = "hidden";
const gif = await giphyRandom(API_KEY, {
tag: "kawaii"
});
const {url} = gif.data; // equal to const url = gif.data.url
console.log(gif);
}

Fetch API - storing a html file in a variable then query the variable contents

Pretty novice to Javascript. So any help would be great.
I'm using the fetch to retrieve html from a search like below:
var downloadHtml;
fetch(
'https://cors-
anywhere.herokuapp.com/https://www.youtube.com/results?
search_query=A+Song'
)
.then(r => r.text())
.then(data => (downloadHTML = data))
Is it then possible to call another function or perform matches on the downloaded content. So in the method below if you was to execute this on the basepage of the Url in question it would return the list on all the video tags in question.
let GetSongLinks = () => {
var songs = []
let count = document.querySelectorAll('a#video-title.yt-
simple-endpoint.style-scope.ytd-video-renderer').length;
const baseUrl = 'https://www.youtube.com/watch?v='
for (var i = 0; i < count; i++) {
let baseSong = document.querySelectorAll
('a#video-title.yt-simple-endpoint.style-scope.ytd-video-
renderer')[i].innerText
let songId = document.querySelectorAll
('a#video-title.yt-simple-endpoint.style-scope.ytd-video-
renderer'
)[i].data.watchEndpoint.videoId
console.log(songs.push( baseSong + ' - ' + baseUrl + songId))
}
}
Is it possible to either call this function after the promise has been returned and pass data to the function to query these? Or is there a way to scrape the downloadHtml into the variable to find these values? Or even if this is possible? or not? Any suggestions would be appreciated.
As I understand it you can definitely invoke a cleaning method like that inside .then(). It comes down to style. Have the method take in data, and invoke it in your second .then().
There could be ways to scrape your data. It's hard without seeing the data. Consider posting a snippet of the data you get back.

Categories

Resources