- Learn How to Use the Express Generator
- Use our learned methods to structure our application
- Perform CRUD on a resource
- Set up our express app, learn more about the generator
- Model our application with our preferred data structure in mind
- Use RESTful approaches when setting up our app
- Use and Examine the Module Exports Pattern
- We are going to be setting up a single model application that will allow us to do data modeling, use RESTful routes, and write our own module that will act like a database
- the application we will be building is a blog
- use past conventions we have learned to help guide us to build a new one
- this lesson we are going to reference this guide like we did when learning rails. This guide can serve as a resource when you are doing this on your own.
- We are going to set up our blog application, and we are going to use the
express generatorinstead of setting it up by hand. - When using the express generator, we get to see conventions that will remind us of rails
- When learning a new framework and language, it is often very adventageous to us scaffolds so we can see how really smart people structure their apps
- let's
cdinto the section of your computer where you like putting your projects. once there, we are going to put our app in there - for me, that's my root
~/ - once there, let's run this command
express first-blog -e
- once we run the above command, we will see some output instructions to set up our application further
- follow those instructions to now run
cd firstblog && npm install - from yesterday, we learned about NPM install. what does it do?
- now let's make another change: let's change the name of our
app.jstoserver.js. We must also make another change for that in ourbin/wwwdirectory - why did we change this file?
- with our app scaffolded and our files changed, lets get to localhost.
- now that we have scaffolded our app with
express <name> -e, rannpm installto install our dependencies, and followed a convention by changing the name of our file, we just have to launch our app - now run
npm startfrom the base of your repo, and navigate your browser tohttp://localhost:3000/you should see this
- with the majority of our boilerplate done and taken care of, we can now move onto the structure of our application and add real stuff to it.
- we are going to be building a blog application, one that we could use to document our WDI journey's.
- let's start by adding one additional view to our application to get a feel for how it might work
- in our
routes/index.ejsfile, let's go in an add a new route- we are going to call this route
About, so before i make my route I am going to add a view. make a new fileviews/about.ejsand save it - next in our
routes/index.jslet's add this
- we are going to call this route
router.get('/about', function(req, res) {
res.render('about', {
title: 'About',
description: "PBR&B prism woke pour-over. Semiotics bushwick dreamcatcher, \
kitsch hell of glossier cold-pressed humblebrag meditation kogi wayfarers leggings hot chicken cliche butcher. \
Etsy vexillologist post-ironic kombucha mustache chicharrones, lo-fi mlkshk. Typewriter williamsburg pinterest brunch. \
Pabst man braid williamsburg butcher freegan, selfies slow-carb. Microdosing post-ironic YOLO vegan, single-origin coffee offal etsy. \
Etsy 8-bit venmo, lyft migas gochujang try-hard chambray celiac selvage taxidermy coloring book."
});
}); - Then let's go inside our newly created
about.ejsfile inside our views folder, and let's add a new view to reflect our new route
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<p>Welcome to <%= title %> stuff</p>
<p><%= description %></p>
</body>
</html>- now if we
CONTROL-Cand restart our server w/npm start, we can navigate tohttp://localhost:3000/aboutto see our new route
- Now that we have our app set up, and we can add new routes and receieve pages w/ dynamic data, let's add our data.
- Since we're building a blog, we should add support for listing a set of blog entries on the home page and allowing you to link to a particular blog entry.
- Instead of setting up a connection to a database, let's start the creation of a javascript module that will act like our database
- In the base of your app, let's add a file called
post.jsthat will "seed" our app with a couple sample posts. Add this to that file
var entries = [
{"id":1, "title":"Hello World!", "body":"This is the body of my blog entry. First Entry!", "published":"01/01/2017"},
{"id":2, "title":"Eggs for Breakfast", "body":"Today I had eggs for breakfast. Sooo exciting.", "published":"01/10/2017"},
{"id":3, "title":"Ruby is Awesome", "body":"News Flash! Ruby is awesome!", "published":"01/15/2017"},
{"id":4, "title":"Javascript is Cool", "body":"This Just In! Javascript is cool.", "published":"01/17/2017"},
{"id":5, "title":"I'm Leaving Technology X and You Care", "body":"Let me write some link bait about why I'm not using a particular technology anymore.", "published":"01/20/2017"},
{"id":6, "title":"Help My Kickstarter", "body":"I want a new XBox One. Please fund my Kickstarter.", "published":"01/23/2017"}
];- We can think of the data we just added as that, our data that might come from maybe a database or even an API. But this data in an of itself doesnt do much, we should add some functionality to manipulate it.
- Go back to your
post.jsfile, and let's add a couple methods to mimick aindexandshow.
// "index"
exports.getBlogEntries = function() {
return entries;
}
// "show"
exports.getBlogEntry = function(id) {
for(var i=0; i < entries.length; i++) {
if (entries[i].id == id) {
return entries[i];
}
}
}- With our "model" now set up, let's add to the rest of our app.
- First, let's edit some of our routing. We want to keep our
routes/index.jsfile, but we're not going to be usingusers, so let's delete theroutes/users.jsfile - let's also delete lines 9 and 26 from our
server.js - now, inside our
routesfolder, let's add a new file,posts.jsto handle the routing for all our posts - inside our
posts.jsfile, let's add this
var express = require('express');
var router = express.Router();
var post = require('../post');
router.get('/', function(req, res) {
res.render('posts/index', { title: "My Blog", posts: post.getBlogEntries() });
})
router.get('/:id', function(req, res) {
var entry = post.getBlogEntry(req.params.id);
res.render('posts/show', { title: entry.title, post: entry });
})
module.exports = router- this adds our "index" and "show" actions to our controller and allows us to attach a route to them
- inside of our
server.jswhere ouruserspath/route was, let's now add the route for our posts path - where we deleted the lines for our unused
usersresource, let's add ourpostsresource to those lines
line 9: var posts = require('./routes/posts');
line 28: app.use('/posts', posts);- now that we have our index page, let's add a show page to see our individual posts
- go into your project folder and run
touch views/posts/show.ejs - open that file and let's add some code to it
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1 style="text-align:center;"><%= post.title %></h1>
<span><%= post.published %></span>
<p><%= post.body %></p>
</ul>
</body>
</html>-
now that we have all of the above info in our app, we have our data, we have our index and show, we just need to link them!
-
if we go into our browsers we can navigate to the show page by typing it in, but that's no fun so let's programatically do that.
-
unlike rails, we don't get any cool helpers and have to set all this up manually. but using the information we already know, let's break down how we could link our pages together using regular old
atags- we have the id's from our data in
post.js - we can interpolate string in
ejslike we would in erb
- we have the id's from our data in
-
let's see if we could make this happen! inside our
posts/index.ejslet's add this code inside theulblock
<ul>
<% posts.forEach(function(post) { %>
<p><a href="/posts/<%= post.id %>"><%= post.title %></a></p>
<p><%= post.body %></p>
<hr>
<% }); %>
</ul>- what we do here is manually add our route path inside the
atag by using the id that is attached to the post object - try it out!
- so far we've set up almost all our functionality, but let's add one more route to here
- we are going to make a form with a post action to create a new blog post
- let's start by setting up our route for our
newroute
router.get('/new', function(req, res) {
res.render('posts/new', { title: 'Add New Post' });
});- Once we have our new route, let's add a template for that route. Make a new file at
views/posts/newand let's add this
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1 style="text-align:center;">Add New Post</h1>
<form action="/posts" method="POST">
<label>Title</label>
<input type="text" name="postTitle"><br>
<label>Body</label>
<input type="text" name="postBody"><br>
<input type="submit" value="Add Post">
</form>
</body>
</html>- once we have our form, let's head back to our controller to add our first post route
router.post('/', function(req, res) {
var id = post.entries.length + 1;
var title = req.body.postTitle;
var body = req.body.postBody;
var date = '01/24/2017';
post.entries.push({id: id, title: title, body: body, published: date})
res.render('posts/index', { title: "My Blog", posts: post.getBlogEntries() } );
});- if we head back to our
posts/newpage, we will see a simple form and we should be able to fill it out. - once we fill it out, we will be redirected back to index
- while we are on index, look for the post you just created and click on it!
- for the next 20-30 minutes, you and a partner get together to finish the rest of our RESTful routes
- we have index, show, and create. Your job is to finish update and destroy!

