I am trying to display individual movie objects from array when someone types, for example , localhost:5050/api/movies/1, then I would display Citizen Kane. I can display the array and the welcome message but I keep getting the following message when I try with the id 'Cannot GET /api/movies/1'. Can anyone help me with this? Thanks in advance
enter code here
const express = require("express");
const app = express();
const port = 5050;
app.get("/", (req, res) => {
res.send("Welcome to my favourite movie list");
});
app.get("/api/movies/", function (request, response) {
response.status(200).json(movies);
});
app.get("api/movies/:id", function (request, response) {
response.send("movies " req.params.id);
});
const movies = [
{
id: 1,
title: "Citizen Kane",
director: "Orson Wells",
year: "1941",
colors: false,
duration: 120,
},
{
id: 2,
title: "The Godfather",
director: "Francis Ford Coppola",
year: "1972",
colors: true,
duration: 180,
},
{
id: 3,
title: "Pulp Fiction",
director: "Quentin Tarantino",
year: "1994",
color: true,
duration: 180,
},
];
app.listen(port, (err) => {
if (err) {
console.error("Something bad happened");
} else {
console.log(`Server is listening on ${port}`);
}
});
CodePudding user response:
As @jfriend00 points out, the URL of your GET request should begin with a forward slash. Next you will want to change:
response.send("movies " req.params.id);
to something like...
response.status(200).json({"movie": movies[req.params.id] })
I also see that in some places you use req
and res
but in other places you use request
and response
. You might want to be consistent in order to avoid mistakes.