我尝试对特定ID进行响应。 取而代之的是,我在控制台上无法找到...
例如,如果我要冲浪=> http://localhost:3005/api/books/1,则需要查看第一本书的详细信息: {id:1,作者:“或”,价格:250}
我可以寻求帮助吗?
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"));
答案 0 :(得分:2)
您有错字。
params
,而不是param
答案 1 :(得分:0)
我提前道歉,我的英语水平很差,所以我无法解释您错了,但这是解决您问题的代码
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"));