Skip to content

Instantly share code, notes, and snippets.

@jnewman12
Last active January 24, 2017 18:04
Show Gist options
  • Select an option

  • Save jnewman12/099e22188019d0459a6571dcccc3ecec to your computer and use it in GitHub Desktop.

Select an option

Save jnewman12/099e22188019d0459a6571dcccc3ecec to your computer and use it in GitHub Desktop.
Express App Walkthrough

Express App Walk Through

express


Lesson Objectives

  • Learn How to Use the Express Generator
  • Use our learned methods to structure our application
  • Perform CRUD on a resource

Roadmap

  • 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

Intro

  • 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

A note

  • 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.

Project Set Up

  • We are going to set up our blog application, and we are going to use the express generator instead 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

Set up Continued

  • let's cd into 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

Examining our application

  • once we run the above command, we will see some output instructions to set up our application further

express output

  • 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.js to server.js. We must also make another change for that in our bin/www directory
  • why did we change this file?

Getting to LocalHost

  • with our app scaffolded and our files changed, lets get to localhost.
  • now that we have scaffolded our app with express <name> -e, ran npm install to install our dependencies, and followed a convention by changing the name of our file, we just have to launch our app
  • now run npm start from the base of your repo, and navigate your browser to http://localhost:3000/ you should see this

express 3000


Starting our App

  • 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.ejs file, 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 file views/about.ejs and save it
    • next in our routes/index.js let's add this
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.ejs file 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-C and restart our server w/ npm start, we can navigate to http://localhost:3000/about to see our new route

Adding our Data

  • 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.js that 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.js file, and let's add a couple methods to mimick a index and show.
// "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.js file, but we're not going to be using users, so let's delete the routes/users.js file
  • let's also delete lines 9 and 26 from our server.js
  • now, inside our routes folder, let's add a new file, posts.js to handle the routing for all our posts
  • inside our posts.js file, 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.js where our users path/route was, let's now add the route for our posts path
  • where we deleted the lines for our unused users resource, let's add our posts resource to those lines
line 9:  var posts = require('./routes/posts');
line 28: app.use('/posts', posts);

Show

  • 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>

Manual Link to's

  • 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 a tags

    • we have the id's from our data in post.js
    • we can interpolate string in ejs like we would in erb
  • let's see if we could make this happen! inside our posts/index.ejs let's add this code inside the ul block

<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 a tag by using the id that is attached to the post object
  • try it out!

The Create Action

  • 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 new route
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/new and 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/new page, 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!

Your Turn

  • 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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment