如何在 Express 中将数据从服务器发送到客户端
how to send data from server to client in Express
我想为我的网站制作一个显示所有用户姓名的页面
<!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>
但是当我使用 fetch() 函数从服务器获取数据时,响应是空的,它没有给我发回的数据
服务器代码:
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 })
})
好像 res.json() 不工作,请有人帮助我,我认为问题是在 URL HTTP://localhost:3000/api/users, // 被视为注释,因此 // 之后的所有内容都是注释,如果为真,则不会被执行或忽略 JavaScript 如何发送请求
当使用提取 API 时,来自服务器的数据可从 JSON 对象中的函数 json() 获得。
您需要调用 res.json() 函数。这将 return 一个对象。您可以循环遍历对象并以这种方式访问对象中键的值:
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();
我想为我的网站制作一个显示所有用户姓名的页面
<!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>
但是当我使用 fetch() 函数从服务器获取数据时,响应是空的,它没有给我发回的数据
服务器代码:
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 })
})
好像 res.json() 不工作,请有人帮助我,我认为问题是在 URL HTTP://localhost:3000/api/users, // 被视为注释,因此 // 之后的所有内容都是注释,如果为真,则不会被执行或忽略 JavaScript 如何发送请求
当使用提取 API 时,来自服务器的数据可从 JSON 对象中的函数 json() 获得。 您需要调用 res.json() 函数。这将 return 一个对象。您可以循环遍历对象并以这种方式访问对象中键的值:
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();