为什么它只有 returns 我的模拟数据库中的第一个 ID?
Why it only returns the first id from my mock up database?
简而言之,我正在尝试创建一个简单的 api,它将 return 具有匹配 ID 的用户。我使用邮递员将请求发送到使用 node.js 和 express 创建的本地主机。当我请求第一个用户时它工作正常但在请求“John”时抛出错误。我正在编写一个 udemy 课程,除了 material 已经过时之外无法弄清楚问题是什么。错误是“错误 [ERR_HTTP_HEADERS_SENT]:将它们发送到客户端后无法设置 headers”
users: [
{
id: "123",
name: "Sally",
email: "sally@gmail.com",
password: "bananas",
entries: 0,
joined: new Date(),
},
{
id: "124",
name: "John",
email: "john@gmail.com",
password: "apples",
entries: 0,
joined: new Date(),
},
],
};
app.get("/profile/:id", (req, res) => {
const { id } = req.params;
let found = false;
database.users.forEach((user) => {
if (user.id === id) {
found = true;
return res.json(user);
}
if (!found) {
res.json("User not found");
}
});
});
来自MDN Web Docs:
There is no way to stop or break a forEach()
loop other than by throwing an exception. If you need such behavior, the forEach()
method is the wrong tool.
Early termination may be accomplished with:
- A simple loop
- A
for
...of
loop
- [
Array.prototype.every()
][every]
- [
Array.prototype.some()
][some]
- [
Array.prototype.find()
][find]
- [
Array.prototype.findIndex()
][findIndex]
这意味着您的循环将 运行 遍历所有元素并且实际上会多次调用 res.json
导致 ERR_HTTP_HEADERS_SENT
错误。有很多方法可以解决这个问题,这里有一个例子:
app.get("/profile/:id", (req, res) => {
const {id} = req.params;
for (const user of database.users) {
if (user.id === id) {
return res.json(user);
}
}
res.json("User not found");
});
简而言之,我正在尝试创建一个简单的 api,它将 return 具有匹配 ID 的用户。我使用邮递员将请求发送到使用 node.js 和 express 创建的本地主机。当我请求第一个用户时它工作正常但在请求“John”时抛出错误。我正在编写一个 udemy 课程,除了 material 已经过时之外无法弄清楚问题是什么。错误是“错误 [ERR_HTTP_HEADERS_SENT]:将它们发送到客户端后无法设置 headers”
users: [
{
id: "123",
name: "Sally",
email: "sally@gmail.com",
password: "bananas",
entries: 0,
joined: new Date(),
},
{
id: "124",
name: "John",
email: "john@gmail.com",
password: "apples",
entries: 0,
joined: new Date(),
},
],
};
app.get("/profile/:id", (req, res) => {
const { id } = req.params;
let found = false;
database.users.forEach((user) => {
if (user.id === id) {
found = true;
return res.json(user);
}
if (!found) {
res.json("User not found");
}
});
});
来自MDN Web Docs:
There is no way to stop or break a
forEach()
loop other than by throwing an exception. If you need such behavior, theforEach()
method is the wrong tool.Early termination may be accomplished with:
- A simple loop
- A
for
...of
loop- [
Array.prototype.every()
][every]- [
Array.prototype.some()
][some]- [
Array.prototype.find()
][find]- [
Array.prototype.findIndex()
][findIndex]
这意味着您的循环将 运行 遍历所有元素并且实际上会多次调用 res.json
导致 ERR_HTTP_HEADERS_SENT
错误。有很多方法可以解决这个问题,这里有一个例子:
app.get("/profile/:id", (req, res) => {
const {id} = req.params;
for (const user of database.users) {
if (user.id === id) {
return res.json(user);
}
}
res.json("User not found");
});