I am trying to understand basics of "express" package of JS and I am stuck with getting array elements based on index that comes from URL.
Here is my code, this is almost a copy of udemy instructor's code, I was writing simultaneosly.
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}`));
Localhost page reaches status 404, user is not found. Problem is ,most probably, about the line:
const user = users.find(c => c.id === parseInt(req.param.id));
Can someone help me to fix this?
I think you're looking in the wrong place.
Express provides the route params in the req.params
not the req.param
.
Maybe changing it to:
parseInt(req.params.id, 10)
will help you