Basic Fetch API listing only the template [duplicate] - javascript

This question already has answers here:
Template literals like 'some ${string}' or "some ${string}" are not working
(7 answers)
How can I do string interpolation in JavaScript?
(21 answers)
Closed 4 months ago.
I am attempting to fetch an API for the user names. but instead of listing names it lists {user.name} rather than the actual names.
How it should look like:
How it ends up looking:
The code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Users</title>
</head>
<body>
<h2>Users:</h2>
<ul></ul>
<script>
fetch('https://jsonplaceholder.typicode.com/users')
.then(res => {
return res.json();
})
.then(data => {
data.forEach(user => {
const markup = '<li>${user.name}</li>';
document.querySelector('ul').insertAdjacentHTML('beforeend', markup);
});
})
.catch(error => console.log(error));
</script>
</body>
</html>
What am I doing wrong?

Related

Trying to fetch and display image from api using javascript?

I am currently building a football website using LiveScore API to fetch data. Needless to say, I am actually learning API fetch using this project. This api fetch current day's fixture. I tried to get the two teams T1 and T2 with their name playing against each other in my HTML file. I got the output below.
Output and api
There are overall 81 arrays, and I want to display logo of the team which is in T1 and T2 array in Img section just before the team name. But only a placeholder is displaying. What am I doing wrong?
I wrote some HTML and JS to fetch the data.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Football Live Today</title>
</head>
<body>
<div>
<h2>Football Live Today</h2>
<h3>Today's Fixtures</h3>
<ul>
<li id="fixtures"></li>
</ul>
</div>
<script src="popup.js"></script>
</body>
</html>
JS
async function fetchData() {
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': '********',
'X-RapidAPI-Host': 'livescore6.p.rapidapi.com'
}
};
const res = await fetch('https://livescore6.p.rapidapi.com/matches/v2/list-by-date?Category=soccer&Date=20231801&Timezone=-7', options)
const record = await res.json()
console.log('record', record)
const indices = [0, 1, 4, 49, 50];
const filteredStages = record.Stages.filter((stage, index) => indices.includes(index));
document.getElementById("fixtures").innerHTML = filteredStages.map(item => `
<li>${item.Cnm} | ${item.Snm} | <img src="('${item.Events[0].T1[0].Img}">
${item.Events[0].T1[0].Nm} Vs <img src="${item.Events[0].T2[0].Img}">
${item.Events[0].T2[0].Nm}</li>`);
}
fetchData();

Exported functions are not defined. Parcel/Browserify

When I use a bundler to make my JS browser compatible my exported functions are not exported.
Error: (index):11 Uncaught TypeError: connect is not a function
at HTMLButtonElement.onclick ((index):11:46)
index.js (Same root file as index.html)
const {ethers} = require("ethers");
async function connect() {
if (typeof window.ethereum !== 'undefined') {
await ethereum.request({method: "eth_requestAccounts"});
}
}
module.exports = {
connect
}
index.html (Same root file as index.js)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>HTML 5 Boilerplate</title>
<script src="./index.js" type="module"></script>
</head>
<body>
<button id="connect" onclick="connect()"> Connect </button>
</body>
</html>
Using parcel, which auto creates a dist file and starts a local server.
Also tried browserify and had same issue.
Parcel supports script tag/elements of type module.
This code works for me but window.ethereum is undefined, it's related to MetaMask no?
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>HTML 5 Boilerplate</title>
</head>
<body>
<button id="connect">Connect</button>
<script type="module">
//Import your module
import something from "./index.js";
//Assign event listener to button
document
.getElementById("connect")
.addEventListener("click", function (event) {
something.connect();
});
console.log("something", something);
/* JavaScript module code here */
</script>
</body>
</html>
index.js
const { ethers } = require("ethers");
async function connect() {
console.log("Inside connect function");
console.log("window.etherum", window.ethereum);
console.log("ethers", ethers);
if (typeof window.ethereum !== "undefined") {
await ethereum.request({ method: "eth_requestAccounts" });
}
}
module.exports = {
connect,
};

how to solve Cannot read property 'name' of undefined in express js?

I'm not able to perform the routing with the parameter, I'm getting the error cant read property 'name'. I used the template engine twig.
Here is my template,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{About}}</title>
</head>
<body>
<P><h1>{{user}}</h1></P>
<P><h2>{{text}}</h2></P>
</body>
</html>
this is my main 'js' file-
const express=require('express')
const app=express()
app.use('./static',express.static('twig templet'))
app.set('view engine', 'twig')
app.set('views','./twig templet/views')
app.get('/',(res,req)=>{
req.render('index',{title:'EXPRESS',gred:'Hello-welcome to Express',mes:'This is twig file'})
})
app.get('/about/:name',(res,req)=>{
res.render('about',{About:'User',user:req.params.name,text:'This is twig file'})
console.log('user is:'+ req.params.name)
})
app.get('/calculation/:a-:b',(res,req)=>{
res.render('calculator',
{About1:'Calculation',
add:parseInt(req.params.a) + parseInt(req.params.b),
sub:parseInt(req.params.a) - parseInt(req.params.b),
mul:parseInt(req.params.a) * parseInt(req.params.b),
div:parseInt(req.params.a) / parseInt(req.params.b)})
//console.log('user is:'+ res.params.Name)
})
app.listen(5000,()=>{
console.log("server is running at 5000")
})
You have the callback values from the app.get() in the wrong order, it should be like this, you can omit the next though,
app.get('/about/:name',(req, res, next) => {}
That's it.

displaying api response on html page

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JSON Test</title>
</head>
<body>
<h1>Hello World</h1>
<div id="myData"></div>
<script>
fetch('http://localhost:3000/api/product/1234567')
.then(function (response) {
return response.json();
})
.then(function (data) {
appendData(data);
})
.catch(function (err) {
console.log('error: ' + err);
});
function appendData(data) {
console.log(data)
var mainContainer = document.getElementById("myData");
for (let key in data) {
var div = document.createElement("div");
div.innerHTML = 'name: ' + data[key] + 'label' + data[key];
mainContainer.appendChild(div);
}
}
</script>
</body>
</html>
Trying to fetch the json response and display it on html page. It's giving me an error: SyntaxError: Unexpected end of JSON input. I guess I'm here to maybe get some help on how to fix this and why this is happening. Thank you.
edit:
The response I get on my console :
{
product: 1234567,
name: 'TV',
salePrice: 149.99
}
The major reason is your response is not in the JSON format, which could be because of getting some non-json format response. Please post the sample JSON response format to understand better.

Exporting object in Webpack 5

I'm building a JS library with Webpack and trying to export an object.
import jwt_decode from "jwt-decode";
console.log(location.hash.replace('#', ''));
export var upstream = {
user: {
getUserDetails: () => {
if (location.hash) {
return jwt_decode(location.hash.replace('#', ''));
} else {
return null;
}
}
}
}
In my client-side code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>UpStream</title>
</head>
<body>
<script src="http://localhost:8080/app.js"> <!--server is up, connects fine-->
</script>
<script>
console.log(upstream);
</script>
</body>
</html>
The console.log(); statement works as intended, but I cannot access the upstream object. Any pointers?
To be able to access upstream via window or just upstream you would need to ensure you specify the export as a Library with libraryTarget of 'window'.
Hopefully that helps!

Categories

Resources