0
app.get("/posts/:postName", (req, res) => {
    var orgpost = req.params.postName;
    posts.forEach(post => {
        if (orgpost === post.post_title) {
            res.render("post", {
                req_title: post.post_title,
                req_body: post.post_body

            });
        }
    });
});

The render here is not working!! Except this all are working

1 Answers1

0

I had a similar issue. If it’s just the CSS, a common issue I read was putting a ‘/’ in front of the link to your local folder. If yours looks like this:

<link rel="stylesheet" href="css/styles.css">

then add this:

<link rel="stylesheet" href="/css/styles.css">

Otherwise, I had a similar issue, but I found that it was because we are using res and how the middleware behaves. Here’s a good explanation on how to use the Node/Express response methods in this well written answer.

Basically, within your forEach loop you are only rendering something for the if statement but not the else statement. It has to do with the middleware items and how they respond problematically when they can’t call response.end() but your loop is forcing continuous iterations, and so you’ll be endlessly loading. This is probably why when I stopped Node I found that it would actually render my page.

Here is the solution that worked for me and adapted for your code:

app.get('/posts/:postName', (req, res) => {
  const orgpost = req.params.postName;
  let pageFound = false;
  posts.forEach(post => {
    if (orgpost === post.post_title) {
      pageFound = true;
      console.log("Match found!")
      res.render('post', {
        req_title: post.post_title,
        content: post.post_body
      });
    }
  });
  if (!pageFound) {
    console.log("Not a match");
    res.redirect('/');
  }
});

By using res outside of the forEach loop, when we do our request it doesn't loop. In this case I used res.redirect().

Dharman
  • 30,962
  • 25
  • 85
  • 135