0

我试图了解 JS 的“express”包的基础知识,但我一直坚持根据来自 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));

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

4

1 回答 1

1

我想你找错地方了。req.paramsExpress 在not 中提供了路由参数req.param

也许将其更改为: parseInt(req.params.id, 10)将对您有所帮助

于 2019-06-23T16:50:38.463 回答