Reputation: 1
I tried to make a get response for a specific id. Instead of that, I get undefind on the console ...
For example, If I'll surf to => http://localhost:3005/api/books/1 I need to see the details of book 1: { id: 1, author: "Or", price: 250 }
Can I get some help?
const express = require("express");
const server = express();
const books = [
{ id: 1, author: "Or", price: 250 },
{ id: 240, author: "Shay", price: 100 },
{ id: 3, author: "Hila", price: 70 },
];
server.get("/api/books", (request, response) => {
response.json(books);
});
server.get("/api/books/:id", (request, response) => {
const id = +request.param.id;
const oneBook = books.find((b) => b.id === id);
console.log(oneBook);
response.json(oneBook);
});
server.listen(3005, () => console.log("Listening on http://localhost:3005"));
Upvotes: 0
Views: 239
Reputation: 5
I apologize in advance my level of English is very bad, so I can’t explain where you were wrong, but here is the code that solves your problem
const express = require("express");
const server = express();
const books = [
{ id: 1, author: "Or", price: 250 },
{ id: 240, author: "Shay", price: 100 },
{ id: 3, author: "Hila", price: 70 },
];
server.get("/api/books", (request, response) => {
response.json(books);
});
server.get("/api/books/:id", (request, response) => {
const { id } = request.params
const oneBook = books.filter(
item => item.id === (+id)
)
console.log(oneBook);
response.json(oneBook);
});
server.listen(3005, () => console.log("Listening on http://localhost:3005"));
Upvotes: 0