Node.js - 将端点快速路由到数组内的 Object 键值
Node.js - Express routing endpoint to Object Key Value inside array
我创建了一个本地服务器来学习和练习我的后端编码。现在它正处于成为“Netflix”风格应用程序的早期阶段。我有一个代码:
app.get("/movies/:title", (req, res) => {
res.json(movies.find((movie) => {
return movie.title === req.params.title
}));
});
当我键入此 URL: localhost:8080/movies/:title(插入标题名称)时,它 returns 所需的电影形成此数组:
let movies = [
//1
{
title: 'Lord of the Rings',
actor: 'Orlando',
genre: 'adventure',
director: 'person'
} ,
//2
{
title: 'Harry Potter',
actor: 'Daniel Radcliffe',
genre: 'Fantasy',
director: 'person',
Movie_ID: "7"
} ,
//3
{
title: 'Imaginaerum',
actor: 'Toumas Holopainen',
genre: 'Fiction',
director: 'person',
Movie_ID: "1"
} ,
//4
{
title: 'Cloud Atlas',
actor: 'Person',
genre: 'Fantasy',
director: 'person'
}
然而,当我尝试做同样的事情时,但在此 URL 中使用键值“actor”:
localhost:8080/movies/:actor(替换为演员姓名)
没有显示任何内容。这是相关代码:
app.get("/movies/:actor", (req, res) => {
console.log(req.params)
res.json(movies.find(movie => {
return movie.actor === req.params.actor
}));
});
非常感谢所有帮助!
正如@Đăng Khoa Đinh 所解释的那样,这些是相同的路线,因此您的代码不知道要使用哪个端点。
将一个改为:
/movies/actor/:actor/
和另一个 /movies/title/:title
或类似的更改以使其正常工作。
我创建了一个本地服务器来学习和练习我的后端编码。现在它正处于成为“Netflix”风格应用程序的早期阶段。我有一个代码:
app.get("/movies/:title", (req, res) => {
res.json(movies.find((movie) => {
return movie.title === req.params.title
}));
});
当我键入此 URL: localhost:8080/movies/:title(插入标题名称)时,它 returns 所需的电影形成此数组:
let movies = [
//1
{
title: 'Lord of the Rings',
actor: 'Orlando',
genre: 'adventure',
director: 'person'
} ,
//2
{
title: 'Harry Potter',
actor: 'Daniel Radcliffe',
genre: 'Fantasy',
director: 'person',
Movie_ID: "7"
} ,
//3
{
title: 'Imaginaerum',
actor: 'Toumas Holopainen',
genre: 'Fiction',
director: 'person',
Movie_ID: "1"
} ,
//4
{
title: 'Cloud Atlas',
actor: 'Person',
genre: 'Fantasy',
director: 'person'
}
然而,当我尝试做同样的事情时,但在此 URL 中使用键值“actor”: localhost:8080/movies/:actor(替换为演员姓名)
没有显示任何内容。这是相关代码:
app.get("/movies/:actor", (req, res) => {
console.log(req.params)
res.json(movies.find(movie => {
return movie.actor === req.params.actor
}));
});
非常感谢所有帮助!
正如@Đăng Khoa Đinh 所解释的那样,这些是相同的路线,因此您的代码不知道要使用哪个端点。
将一个改为:
/movies/actor/:actor/
和另一个 /movies/title/:title
或类似的更改以使其正常工作。