Skip to content
Advertisement

Node.js – Express routing endpoint to Object Key Value inside array

I have a local server that I have created to learn and practice my backend coding. Right now its in the early stages of becoming a “netflix” style app. I have a code:

app.get("/movies/:title", (req, res) => {
res.json(movies.find((movie) => {
    return movie.title === req.params.title
}));

});

that when I type this URL: localhost:8080/movies/:title (insert title name) it returns the desired movie form this array:

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'
}

However, when I try to do the same, but with the key value “actor” in this URL: localhost:8080/movies/:actor (replace for actor name)

nothing shows up. Here is the code for that:

app.get("/movies/:actor", (req, res) => {
console.log(req.params)
res.json(movies.find(movie => {
    return movie.actor === req.params.actor
}));
});

All help is greatly appreciated!

Advertisement

Answer

As @Đăng Khoa Đinh explained, these are the same routes, so your code doesn’t know which end point to use.

Change one to:

/movies/actor/:actor/ and the other to /movies/title/:title or a similar change to get this working.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement