【问题标题】:Array.find() method usage with req.param in TypeScriptArray.find() 方法在 TypeScript 中与 req.param 一起使用
【发布时间】:2019-11-05 15:12:33
【问题描述】:

我正在尝试了解 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));

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

【问题讨论】:

  • 开始调试你的代码,比如检查req.param.id的值。但是,请记住,.find() 在未找到任何元素时返回 undefined,而不是 null
  • 你访问的是什么 localhost url?
  • localhost:3000/api/users/1
  • 另外,我将“user === null”部分更改为“!user”,但状态仍然相同 404

标签: javascript node.js typescript express req


【解决方案1】:

我认为你找错地方了。 Express 在req.params 而不是req.param 中提供路由参数。

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

【讨论】:

  • 但 req.params 在 typescript 中无法识别
  • 嘿!你是对的,它给了我想要的结果,但是 param 和 params 有什么区别?
  • 刚刚在req.param 上运行了toString,它似乎是一个返回参数的函数。如果对您有用,请将此答案标记为正确:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-10
  • 2017-01-13
  • 2021-12-29
  • 2017-02-19
  • 2019-06-06
相关资源
最近更新 更多