objectobject returning with async await - javascript

Guys i have this problem with my code
`
get data
<script>
let dataBtn;
async function fetchData() {
const response = await fetch("./prodotti.json");
return await response.json();
}
const container = document.querySelector(".container");
const btn = document.querySelector("#get");
const newDiv = document.createElement("div");
btn.addEventListener("click", async () => {
const data = await fetchData();
//console.log(data);
container.appendChild(newDiv).innerHTML = data.name;
});
</script>
`
when i click on the button appears [object object] instead of the json data

It looks like you get a problem with serialisation of an object what you received from your api. Make sure the data.name is really a string and accessible.Below a working example with another example api to show that your code will work.
let dataBtn;
async function fetchData() {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
return await response.json();
}
const container = document.querySelector(".container");
const btn = document.querySelector("#btnGet");
const newDiv = document.createElement("div");
btn.addEventListener("click", async () => {
const data = await fetchData();
console.log(data);
container.appendChild(newDiv).innerHTML = data.title;
});
<div class="container"></div>
<button id="btnGet">GET</button>

Try to write code like this: data[0]

Related

how to recognize two images using tesseract.js?

Here is my code, I can recognize only one image using tesseract.js (i.e filepath1), I want to recognize both images (filepath1 and filepath2), how to achieve that?
app.post("/",(req,res)=>{
const form = formidable({multiples:true});
form.parse(req,(err,fields,files)=>{
const filepath1 = files.file1.filepath;
const filepath2 = files.file2.filepath;
const worker = createWorker({
logger: m => console.log(m)
});
(async () => {
await worker.load();
await worker.loadLanguage('eng');
await worker.initialize('eng');
const { data: { text } } = await worker.recognize(filepath1);
const replacedtext1 = text.replace(/[^a-zA-Z ]/g, "");
const wordextract1 = replacedtext1.match(/\w+/g);
fileextract1.push(wordextract1);
console.log(wordextract1);
await worker.terminate();
})();
});
});

json api parse object

Good day, I'm trying to get certain values ​​​​with api the maximum that I can do is output all the json
const api_url = 'https://api.battlemetrics.com/servers/3753675'
async function getData() {
const response = await fetch(api_url);
const json = await response.json();
const { data } = json;
console.log(data)
}
getData();
please could tell me how to get the element, I tried like this:
const api_url = 'https://api.battlemetrics.com/servers/3753675'
async function getData() {
const response = await fetch(api_url);
const json = await response.json();
const { name, id, status } = json;
console.log(name, id, status)
}
getData();
but i get "undefined undefined undefined"
The object I asked for:
{"data":{"type":"server","id":"3753675","attributes":{"id":"3753675","name":"Rusticated.com Sandbox - Creative | Minigames | Bedwars\r","address":null,"ip":"199.231.233.240","port":28015,"players":201,"maxPlayers":1000,"rank":1,"location":[-87.618889,41.875744],"status":"online","details":{"official":false,"rust_type":"modded","map":"BuildBattleArenaScrimGames","environment":"w","rust_ent_cnt_i":0,"rust_fps":43680,"rust_fps_avg":43680,"rust_gc_cl":null,"rust_gc_mb":null,"rust_hash":"","rust_headerimage":"https://cdn.discordapp.com/attachments/811789078105554984/832668733184671754/Rusticated_Mini_Games_Banner_512x256.png","rust_mem_pv":null,"rust_mem_ws":null,"pve":false,"rust_uptime":null,"rust_url":"https://rustminigames.com","rust_world_seed":1337,"rust_world_size":null,"rust_description":"Rusticated Minigames Beta \n Bedwars \n Creative \n GunGame \n Targets \n More Coming Soon...","rust_modded":true,"rust_queued_players":0,"rust_born":"2022-06-05T00:00:00.000Z","rust_last_ent_drop":"2021-08-06T00:10:18.261Z","rust_last_seed_change":"2020-09-03T18:33:52.047Z","rust_last_wipe":"2021-08-06T00:10:18.261Z","rust_last_wipe_ent":29035,"serverSteamId":"90159726978107400"},"private":false,"createdAt":"2019-06-18T18:35:26.890Z","updatedAt":"2022-06-06T10:05:57.516Z","portQuery":28038,"country":"US","queryStatus":"valid"},"relationships":{"game":{"data":{"type":"game","id":"rust"}}}},"included":[]}
If you want to get object you said, try this.
const API_URL = 'https://api.battlemetrics.com/servers/3753675';
async function getData() {
const response = await fetch(API_URL);
const json = await response.json();
console.log(json); // you need to check json first. (*)
}
getData();
Then you can use destructuring.
const API_URL = 'https://api.battlemetrics.com/servers/3753675';
async function getData() {
const response = await fetch(API_URL);
const json = await response.json();
const { name, id, status } = json.data.attributes; // (*)
console.log(name, id, status);
}
getData();
You just need to replace:
const { name, id, status } = json;
with:
const {
data: {
id,
attributes: { name, status }
}
} = json;
because your keys are not directly into the response, but nested.

issue to load data from a .js file

I am trying to run a web page with that js file, for some reason, it doesn't want to work and when I try the console it says "Live reload enabled". Does anyone know how I can solve that issue?
.
const container = document.querySelector('.datalink')
let listdata = async() => {
let url = ' http://localhost:3000/indusboards';
const urlfetch = await fetch(url);
const urlfound = await urlfetch.json();
let template = '';
datafound.array.forEach(element => {
template += `
<div class ="element">
<p><small>${element.serialno}</small></p>
<p><small>${element.boardtest}</small></p>
<p><small>${element.testresul}</small></p>
<p><small>${element.serialno}</small></p>
<p><small>${element.testdate}</small></p>
<p><small>${element.testtime}</small></p>
<p><small>${element.boardlocation}</small></p>
.... more
</div>
`
})
container.innerHTML = template;
}
window.addEventListener('DOMContentLoarded', () => listdata());
You made a spelling mistake change your code to.
window.addEventListener('DOMContentLoaded', () => listdata());
Instead of
window.addEventListener('DOMContentLoarded', () => listdata());
or you could use
window.onload = () => {
listdata()
}
How about this?
const container = document.querySelector('.datalink')
let listdata = async() => {
let url = ' http://localhost:3000/indusboards';
const urlfetch = await fetch(url);
const urlfound = await urlfetch.json();
let template = '';
datafound.array.forEach(element => {
template += `
<div class ="element">
<p><small>${element.serialno}</small></p>
<p><small>${element.boardtest}</small></p>
<p><small>${element.testresul}</small></p>
<p><small>${element.serialno}</small></p>
<p><small>${element.testdate}</small></p>
<p><small>${element.testtime}</small></p>
<p><small>${element.boardlocation}</small></p>
.... more
</div>
`
})
container.innerHTML = template;
}
window.addEventListener('DOMContentLoaded', () => listdata());

Search function error: Cannot read property 'results' of undefined

I get data from Marvel API and the data is displayed perfectly.
However, when I try to implement search function, I get this 'Uncaught TypeError: Cannot read property 'results' of undefined at displayData' error.
Here is the code:
const apiUrl = ... ;
let data = [];
const searchBar = document.querySelector("#searchbar");
searchBar.addEventListener("keyup", (e) => {
const searchString = e.target.value.toLowerCase();
const filter = data.data.results.filter((character) =>
character.name.toLowerCase().includes(searchString)
);
displayData(filter);
});
async function getData() {
const response = await fetch(apiUrl);
data = await response.json();
console.log(data);
displayData(data);
const characters = data.data.results;
console.log(characters);
}
const displayData = (data) => {
const characters = data.data.results;
console.log(characters);
for (character of characters) {
document.getElementById("output").innerHTML += `
<div class="character">
<h1>${character.name}</h1>
<a href="${character.urls[0].url}" target="_blank">
<img src="${character.thumbnail.path}.${character.thumbnail.extension}" alt="${character.name}" height="100" class="image" />
</a>
</div>
`;
}
};
These console.log show that I get the data that I want, there is no error until I try to search and then it shows me that the error is on line 26 which is 'const characters = data.data.results;' in displayData function. Any help?
When you call displayData(data) from searchbar event listener, you are passing only a filtered array (without data property), and parameter name data is shadowing global data variable, but when you call displayData from getData function, you are passing the whole data object.
You can try changing the parameter passed to displayData function, and change a call to it from getData function:
const apiUrl = ... ;
let data = [];
const searchBar = document.querySelector("#searchbar");
searchBar.addEventListener("keyup", (e) => {
const searchString = e.target.value.toLowerCase();
const filter = data.data.results.filter((character) =>
character.name.toLowerCase().includes(searchString)
);
displayData(filter);
});
async function getData() {
const response = await fetch(apiUrl);
data = await response.json();
console.log(data);
displayData(data.data.results);
const characters = data.data.results;
console.log(characters);
}
const displayData = (characters) => {
let filteredHTML = '';
for (character of characters) {
filteredHTML += `
<div class="character">
<h1>${character.name}</h1>
<a href="${character.urls[0].url}" target="_blank">
<img src="${character.thumbnail.path}.${character.thumbnail.extension}" alt="${character.name}" height="100" class="image" />
</a>
</div>
`;
};
document.getElementById("output").innerHTML = filteredHTML;
};

Making a web-crawler to have loop

I tried to make my web-crawler to have a loop to crawl the webpage from 1 to around 500. But the result does not include any directed one but to return an only void array.
This code is based on cheerio, jQuery, and axios. JavaScript.
const axios = require("axios");
const cheerio = require("cheerio");
const log = console.log;
const getHtml = async() => {
var i=0
while (i<493){
try {
return await axios.get("https://playentry.org/ds#!/qna?sort=created&rows=20&page="+i);
} catch (error) {
console.error(error);
}
}
};
getHtml()
.then(html => {
let ulList = [];
const $ = cheerio.load(html.data);
const $bodyList = $("div.discussContentWrapper div.discussListWrapper table.discussList").children("tr.discussRow");
$bodyList.each(function(i, elem){
ulList[i] = {
title:$(this).find('td.discussTitle div.discussTitleWrapper'),
writer:$(this).find('td.discussTitle td.discussViewCount'),
viewcount:$(this).find('td.discussTitle td.discussViewCount'),
likecount:$(this).find('td.discussTitle div.discussLikeCount'),
date:$(this).find('td.discussTitle td.discussDate'),
};
});
const data = ulList.filter(n => n.title);
return data;
})
.then(res => log(res));
The output is '''[]''' or '''[ [] ]''' with no real outputs.
Thanks for your help in advance.

Categories

Resources