I want to make a page for my website where it shows the names of all users
<!DOCTYPE HTML>
<html lang="en">
<head>
</head>
<body>
<div class="page">
</div>
<style>
html,
body,
.page {
width: 100%;
height: 100%;
overflow: hidden;
}
.page {
display: grid;
grid-template-columns: repeat(5, auto);
grid-template-rows: repeat(auto, auto);
}
</style>
<script>
const name = localStorage['name']
async function getUsers() {
const page = document.querySelector('.page')
const res = await
fetch('http://localhost:3000/api/users')
console.log(res)
for(const name in res.usersName) {
let userDiv = document.createElement('div')
userDiv.innerHTML = name
userDiv.style.textAlign = "center"
page.append(div)
}
}
getUsers()
</script>
</body>
</html>
but when I use the fetch() function to get the data from the server, the response is nothing it does not give me the data I sent back
the server code:
app.get('/api/users', (req, res) => {
users = database.getAllData()
const usersName = new Array()
for(const user of users) {
usersName.push(user.name)
}
res.json({ usersName })
})
seems like res.json() is not working, please someone to help me, I think that the problem is that in the URL HTTP://localhost:3000/api/users, the // is considered as a comment so everything after the // is a comment and will not be executed or ignored by JavaScript if this is true how to send a request
The data from the server is available from the function json() in the JSON object from the response when using the fetch API. You need to call the res.json() function. This will return an Object. You can loop through an Object and access the value of a key in an Object this way:
const getUsers = async () => {
const res = await fetch("http://localhost:3000/api/users/");
const users = await res.json()
for (const user in users) {
console.log(users[user].name)
}
}
getUsers();