newbie
newbie

Reputation: 85

How to display dynamic pages correcly in expressJS?

My app.js file has the following array of objects:

var people = [
        {name: "Henrique Melo", username: "heenrique", email: "[email protected]"},
        {name: "João Pessoa", username: "jooao", email: "[email protected]"}
    ];

I'm trying to create a page for each person with the following code:

app.get("/:username", function(req, res) {
    for (var i = 0; i < people.length; i++) {
       if (people[i].username === req.params.username) {
            res.render("description.ejs", { pageTitle : "Profile", user : people[i] });
        } else {
            res.status(404).json("User not found.");
        }
    }
});

The description page for the first person in the array ("/heenrique") loads perfectly, but any following object will not be displayed. When I type ("/jooao" - the username of the 2nd person in the array) I get the "user not found" message in my else statement. There must be a problem with the loop I created. Please, shed some light on the issue.

Upvotes: 3

Views: 57

Answers (1)

cardeol
cardeol

Reputation: 2238

The problem is that the loop has to continue for the next item without rendering any error (Error occurs on 1st iteration when people[0] don't match the requested username). A working approach would be like this.

app.get("/:username", function(req, res) {
    for (var i = 0; i < people.length; i++) {
       if (people[i].username === req.params.username) {
            res.render("description.ejs", { pageTitle : "Profile", user : people[i] });
            return;
        }
    }
    res.status(404).json("User not found.");
});

Upvotes: 4

Related Questions