【发布时间】: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