Array.find() 方法在 TypeScript 中与 req.param 的用法

Array.find() method usage with req.param in TypeScript

我正在尝试了解 "express" JS 包的基础知识,但我一直坚持基于来自 URL 的索引获取数组元素。

这是我的代码,这几乎是udemy导师代码的副本,我是同时写的。

const express = require('express');
const app = new express();

const users = [
    { id: 1 , name: "harun" },
    { id: 2 , name:"apo" },
    { id: 3 , name: "ogi" }
]


app.get('/', (req,res) => {
    res.send("Welcome to my Page");
});

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

app.get('/api/users/:id', (req,res) => {
    const user = users.find(c => c.id === parseInt(req.param.id));
    if(user === null) res.status(404).send("User is not found");
    res.send(user);
});


const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port: ${port}`));

本地主机页面状态为 404,未找到用户。 问题很可能是关于这条线:

 const user = users.find(c => c.id === parseInt(req.param.id));

有人可以帮我解决这个问题吗?

我想你找错地方了。 Express 在 req.params 而不是 req.param.

中提供路由参数

也许将其更改为: parseInt(req.params.id, 10) 会帮助你