Individual Blog Posts
Last updated
Last updated
We could make the CMS even better, by making it possible to retrieve and view individual blog posts. Let's take a look at how we can do that.
We don't want to have to write a handler for each URL in our application. Express's let us specify dynamic sections of the a URL - a space for a blog post ID or username, for example. You can think of them as function arguments being passed to your server.
Express's URL parameters use a :
for dynamic parts of the URL:
/users/:userId
- matches URLs like /users/123
, /users/node-girls
/users/:userId/posts/:postId
- matches URLs like /users/node-girls/posts/node-is-best
Let's add a handler for serving individual blog posts:
What do you think you'll see when you visit in your browser?
Just like with , you need to read your JSON file. Try and send the post content back to the browser:res.send(postContentHere)
Right now we're just sending the plain text of your blog post, but you probably want to jazz up your post with some HTML and CSS. For this, we can use Express's built in templating system. You can use any template language you want (like , , or ), but we're going to use (which is very similar to handlebars) in this example.
Give your posts titles
Add a post listing page
Render posts as Markdown
Yay!
Run npm install --save mustache-express
, then check the documentation for and . You'll need to create a template file in views/post.mustache
like this:
If you get stuck, check out the :)