issue to load data from a .js file - javascript

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

Related

objectobject returning with async await

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]

JavaScript, fetch, Netlify: Netlify didn't fetch second response

I've started to learn sass and gave myself a task: create two elements with two independent resources. The image below is what I see in live server in VsCode.
But when I deploying it into netlify, the result is next: .
so i start thinking that problem is my js code:
// Weather
const weatherBlock = document.querySelector('#weather');
async function loadWeather() {
weatherBlock.innerHTML = `
<div class="weather__loading"><img src='assets/loading.gif' alt='Loading...' >
</div>`;
const server =
'https://api.openweathermap.org/data/2.5/weather?units=metric&q=Kyiv&appid=ab54429ab157825232cab97e89867df3';
const response = await fetch(server, {
method: 'GET',
});
const responseResult = await response.json();
if (response.ok) {
getWeather(responseResult);
} else {
weatherBlock.innerHTML = responseResult.message;
}
}
function getWeather(data) {
const location = data.name;
const temp = Math.round(data.main.temp);
const feelsLike = Math.round(data.main.feels_like);
const weatherStatus = data.weather[0].main;
const weatherIcon = data.weather[0].icon;
console.log(data);
const template = `
<div class="weather__header">
<div class="weather__main">
<div class="weather__city">${location}</div>
<div class="weather__status">${weatherStatus}</div>
</div>
<div class="weather__icon">
<img src="http://openweathermap.org/img/w/${weatherIcon}.png" alt="${weatherStatus}">
</div>
</div>
<div class="weather__temp">${temp}</div>
<div class="weather__feels-like">Feels like: ${feelsLike}</div>`;
weatherBlock.innerHTML = template;
}
if (loadWeather) {
loadWeather();
}
// Cat
const catBlock = document.querySelector('#cats');
const catBtn = document.querySelector('.cat-button');
const catImg = document.querySelector('.cat-image');
const catServer = 'http://aws.random.cat/meow';
async function catFetch() {
const catResponse = await fetch (catServer);
const catResponseResult = await catResponse.json();
if (catResponse.ok){
renderCat(catResponseResult);
} else {
catBlock.innerHTML = catResponseResult.message;
}
}
function renderCat(catData) {
const catImgUrl = catData.file
catImg.src = catImgUrl;
}
catBtn.addEventListener('click', catFetch);
if (catFetch){
catFetch()
}
full code: https://github.com/antonkornilov-ua/10-09-2022---Weather-and-Cats

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

Appending data from api into DOM

const url = `https://catfact.ninja/fact?max_length=140`;
const getFact = () => {
return fetch('https://catfact.ninja/fact?max_length=140')
.then(res => res.json())
}
const createFactDiv = (fact) => {
const factContainer = document.createElement('div')
const setup = document.createElement('p')
setup.innerText = fact.fact
factContainer.append(setup)
return factContainer
}
const appendFact = (factDiv) => {
const factContainer = document.getElementById('factContainer')
factContainer.append(FactDiv)
}
document.addEventListener('DOMContentLoaded', () => {
})
getFact().then ((fact) => {
const FactDiv = createFactDiv(fact)
append.fact (FactDiv)
})
I have tried several things, fairly new to JS and it is tricky. I am trying to create an app that displays cat facts. I was seeing the DIV with the FACT inside correctly in the console.log in the elements of the DOM, but now I don't see it and I keep seeing
Uncaught (in promise) ReferenceError: append is not defined
Any idea what to do? Much appreciated !
Yep, it's our old friend spelling errors! Here is some working code:
const url = `https://catfact.ninja/fact?max_length=140`;
const getFact = () => {
return fetch('https://catfact.ninja/fact?max_length=140')
.then(res => res.json())
}
const createFactDiv = (fact) => {
const factContainer = document.createElement('div');
const setup = document.createElement('p');
setup.innerText = fact.fact;
factContainer.append(setup);
return factContainer
}
const appendFact = (factDiv) => {
const factContainer = document.getElementById('factContainer');
factContainer.append(factDiv);
}
//This is unused
/*
document.addEventListener('DOMContentLoaded', () => {
})
*/
getFact().then ((fact) => {
const factDiv = createFactDiv(fact);
appendFact(factDiv);
})
This is why it's important to consistently use camelCase:
In appendFact() you took a factDiv parameter but then tried to use FactDiv, which doesn't exist in that function
As noted by Robin, you typed append.fact(FactDiv) instead of appendFact(FactDiv)
This should be refactored to appendFact(factDiv) to stick with camelCase.
Also watch your spacing, and I like to have semicolons at the end of my lines also!

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