(Express.js) TypeError: Cannot destructure property 'name' of 'users[req.params._id]' as it is undefined

(Express.js) TypeError: Cannot destructure property 'name' of 'users[req.params._id]' as it is undefined

我的代码有问题。这很简单,但我不知道为什么它不returning 带有ID 的对象。我得到的只是上面的错误。

我遵循了另一条与我相同的指示,但仍然如此。

如何return匹配URL中的ID的对象?

我的代码:


const app = express();

// const { PORT = 3000 } = process.env;

app.listen(3000);

app.get('/', (req, res) => {
  res.status(200).send('oh noes uwu :)');
});

app.get('/users', (req, res) => {
  res.send(users);
});

app.get('/cards', (req, res) => {
  res.send(cards);
});

app.get('/users/:_id', (req, res) => {
  const { name } = users[req.params._id];
  res.send(name);
});

const users = [
  {
    name: 'Ada Lovelace',
    about: 'Mathematician, writer',
    avatar: 'https://www.biography.com/.image/t_share/MTE4MDAzNDEwODQwOTQ2MTkw/ada-lovelace-20825279-1-402.jpg',
    _id: 'dbfe53c3c4d568240378b0c6',
  },
  {
    name: 'Tim Berners-Lee',
    about: 'Inventor, scientist',
    avatar: 'https://media.wired.com/photos/5c86f3dd67bf5c2d3c382474/4:3/w_2400,h_1800,c_limit/TBL-RTX6HE9J-(1).jpg',
    _id: 'd285e3dceed844f902650f40',
  },
  {
    name: 'Alan Kay',
    about: 'Computer scientist',
    avatar: 'https://cdn.cultofmac.com/wp-content/uploads/2013/04/AlanKay.jpg',
    _id: '7d8c010a1c97ca2654997a95',
  },
  {
    name: 'Alan Turing',
    about: 'Mathematician, cryptanalyst',
    avatar: 'https://cdn.britannica.com/81/191581-050-8C0A8CD3/Alan-Turing.jpg',
    _id: 'f20c9c560aa652a72cba323f',
  },
  {
    name: 'Bret Victor',
    about: 'Designer, engineer',
    avatar: 'https://postlight.com/wp-content/uploads/2018/03/109TC-e1535047852633.jpg',
    _id: '8340d0ec33270a25f2413b69',
  },
  {
    name: 'Douglas Engelbart',
    about: 'Engineer, inventor',
    avatar: 'https://images.fineartamerica.com/images-medium-large-5/douglas-engelbart-emilio-segre-visual-archivesamerican-institute-of-physics.jpg',
    _id: '3c8c16ee9b1f89a2f8b5e4b2',
  },
];

当您编写 users[[=​​29=]] 时,您正在尝试访问数组特定索引处的对象。现在,如果 URL 参数是 dbfe53c3c4d568240378b0c6,基本上是这样读的:

  1. 获取用户数组,并使用索引 dbfe53c3c4d568240378b0c6
  2. 访问其值
  3. 您的数组没有 属性 具有此索引 -> undefined
  4. 您不能从 undefined 解构 { name }。

你可以做的是遍历用户,例如:

let userName;

for (let user of users) {
    if (user._id === req.params._id) userName = user.name;
}