0

Fair warning I am fairly new to node and may not be asking the correct questions

I am trying to make a blog on my website and would like the show route for my posts to contain a slugified version of the posts title instead of a long ID. An example is example.com/blog-title-here instead of example.com/17489349823789423832. I have installed slugify but I cannot seem to make it work. I am having trouble storing the title's as slugs and any guidance would be extremely welcome.

//SHOW BLOG ROUTE
app.get("/blogs/:slug", function(req, res){
  var slug = slugify(req.body.blog.title);
  Blog.find({ slug: req.params.slug}, function (err, foundBlog) {
      if(err){
          res.redirect("/blogs");
      } else {
          res.render("show", {blog: foundBlog});
      }
  })
});

here is the blog index page with the view post button having an href that I do not think is correct either.

<div class="blog-feed">
            <div class="container">
                    <div class="row">
                        <% blogs.forEach(function(blog){ %>
                            <div class="col-lg-4 mb-4">
                                <div class="card">
                                    <img class="card-img-top" src="<%= blog.image %>" alt="Card image cap">
                                    <div class="card-body text-center">
                                    <h5 class="card-title"><%= blog.title %></h5>
                                    <p class="card-text"><%- blog.body %></p>
                                    <a href="/blogs/<%= blog.slug %>" class="btn btn-primary">View Post</a>
                                    </div>
                                </div>
                            </div>
                        <% }) %>
                    </div>
                </div>
    </div>

Here is how I save the post to the database

//CREATE BLOG ROUTE
app.post("/blogs", function(req, res){
  //create blog
  console.log(req.body);
  req.body.blog.body = req.sanitize(req.body.blog.body)
  console.log("===========");
  console.log(req.body);
  console.log(slugify(req.body.blog.title));
  Blog.create(req.body.blog, function(err, newBlog){
      if(err){
          res.render("blogNew");
      } else {
          //then, redirect to the index
          res.redirect("/blogs");
      }
  })
});

Thank you for your help in advance!

klaurtar
  • 233
  • 3
  • 23
  • You need to use slugify in a route where you save the blog post to the database, some route like `app.post('/api/posts/new',....)` you haven't shown any code related to the saving of the post to db. – Molda Jan 04 '19 at 07:03
  • Ok thanks for pointing that out. I updated my question with my create route which i use to save a post to the database – klaurtar Jan 04 '19 at 07:10
  • So before you save the post you should add the slug `req.body.blog.slug = slugify(req.body.blog.title)` then the route `app.get("/blogs/:slug"` should work – Molda Jan 04 '19 at 07:55

0 Answers0