I'm learning backend and here is an exercise regarding api/express/node.js
The problem is app.get("/api/persons/:person"...
I'm console logging personName
, which is fine, and persons
, which is also fine. But when I do persons[personName]
, it returns undefined.
The result should be returning an individual json object of the person's information.
const express = require("express");
const app = express();
const cors = require("cors");
const PORT = process.env.PORT || 3001;
app.use(cors());
let persons = {
"Arto Hellas": {
id: 1,
name: "Arto Hellas",
number: "040-123456",
},
"Ada Lovelace": {
id: 2,
name: "Ada Lovelace",
number: "39-44-5323523",
},
"Dan Abramov": {
id: 3,
name: "Dan Abramov",
number: "12-43-234345",
},
"Mary Poppendieck": {
id: 4,
name: "Mary Poppendieck",
number: "39-23-6423122",
},
"unknown": {
id: "unknown",
name: "unknown",
number: "unknown"
}
};
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.get("/api/persons", (req, res) => {
res.json(persons);
});
app.get("/api/persons/:person", (req, res) => { // <-- here is the problem
const personName = req.params.person.toLowerCase();
console.log(personName);
console.log(persons);
console.log(persons[personName]);
if (persons[personName]) {
res.json(persons[personName]);
} else {
res.json(persons["unknown"]);
}
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
personName
is converted to lower case, while the keys in persons
are not in lower case. Either change the keys in persons
to be lower case, or remove the toLowerCase()
call when extracting the personName
and call your API with the proper case for the names.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments