Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Workshop: Intro to Node/Express p1

Workshop: Intro to Node/Express p1

Sides for Women Who Code, Intro to Node/Express workshop

Wai-Yin Kwan

April 29, 2016
Tweet

More Decks by Wai-Yin Kwan

Other Decks in Education

Transcript

  1. Static vs Dynamic Sites • back in the olden days,

    people used to hand code each page • as sites got bigger, people moved to programming languages that allowed them to combine data and a few templates to generate the html • our goal is to use Node and Express to create a dynamic site that grabs data from Github API
  2. What is Node? • Before Node, the only place you

    could use javascript was in the browser • Node is a program that executes Javascript outside of the browser. Now people can use javascript in a variety of places, such as on your computer or on a web server. • you can use Node to read/write files, listen to http requests on a server, access database, build utilities to help do development tasks, etc • http://nodejs.org
  3. What is Express? • Express is a framework for Node

    that allows us to build web applications • http://expressjs.com • other web frameworks include Rails/Sinatra for Ruby, Django/Flask for Python, Laravel for PHP
  4. What are packages, npm? • libraries are pre-made code that

    you can use in your software • In Node these libraries are called packages. • npm is the site that hosts the packages • we use “$ npm install” to download packages from npm • https://www.npmjs.com • https://docs.npmjs.com/getting-started/what-is-npm
  5. Step 1 • create a folder for your project. All

    the files will go in this folder. • start a git repo in the folder $ git init
  6. What is package.json? • when you create a project using

    npm, you should add a package.json file • package.json is file that lists information about your project • the information can include author, description, installed packages (dependencies), scripts • https://docs.npmjs.com/getting-started/using-a- package.json
  7. Step 1 • create package.json. • you will be prompted

    to enter in values for series of fields. You can either fill out the fields, or hit enter to use the default values $ npm init
  8. Step 1 • install express • when you type --save,

    the package will be added to package.json in the “dependencies” section • node_modules folder is added, and express is downloaded into the folder • https://docs.npmjs.com/getting-started/installing-npm- packages-locally $ npm install --save express
  9. What is .gitignore? • there are some files that we

    don't want to store in git such as files created by your OS, installed packages, secret config files that has passwords, etc • the installed packages can take up hundreds of megabytes. We don’t want to upload hundreds of megabytes up to github, so we don’t save installed packages to git. • any files or directories listed in .gitignore will not be saved by git • https://git-scm.com/docs/gitignore
  10. Step 1 • check the files that are added •

    you should see node_modules and package.json • we don’t want to store node_modules in git • create .gitignore in the root folder and add this info • check git status again. node_modules should not be listed $ git status node_modules .DS_Store
  11. Step 1 • make the first commit $ git add

    . $ git commit -m ‘install express’
  12. Step 2 • create server.js in the root folder var

    express = require('express'); var app = express(); var port = process.env.PORT || 3000; // ======================= // server // ======================= app.listen(port, function(){ console.log('Server is running on port: ' + port) })
  13. What is require? • require is a command Node uses

    to load modules (code from another file) into current file so that we can use that code • when we pass in the name of an installed package, Node will know to look in node_modules for the package var express = require('express');
  14. What is process.env? • process.env is an object in Node

    that contains the configuration variables for Node • this code means if process.env.PORT has a value, use that value. If process.env.PORT does not have a value, use 3000. var port = process.env.PORT || 3000;
  15. What is app.listen? • app.listen is a command in express

    that tells the app to listen incoming request at a certain port • app.listen has two parameters: port number and a function • this function prints out the message “Server is running on port…” to the terminal app.listen(port, function(){ console.log('Server is running on port: ' + port) })
  16. Step 2 • start the server • you should see

    a message “Server is running on port: 3000” • go to “http://localhost:3000” in your browser. You should see “Cannot GET /” • the reason for the “Cannot GET /“ is we created a server, but we haven’t defined any routes • stop the server by entering control + C. $ node server.js
  17. What are HTTP verbs? • HTTP defines methods (sometimes referred

    to as verbs) to indicate the desired action to be performed on the identified resource. - Wikipedia • Commonly used methods • GET - retrieve data • POST - send data • PUT - update data • DELETE - delete data
  18. Step 2 • add a base route var port =

    process.env.PORT || 3000; // ======================= // routes // ======================= app.get('/', function(request, response) { response.send('hi there'); })
  19. What is app.get? • app.get is the express method used

    to handle incoming GET requests • http://expressjs.com/en/4x/api.html#app.get.method • first argument is the route. ‘/‘ means the base route of the site. • second argument is a callback function. express will execute the function when a request is made to the route. app.get('/', function(request, response) { response.send(‘hi there’); });
  20. What is app.get? • express passes request and response objects

    to the callback. • request contains information about the user who visits the route • response is the information we send back to the user • response.send will send ‘hi there’ to the user • http://expressjs.com/en/4x/api.html#res.send app.get('/', function(request, response) { response.send(‘hi there’); });
  21. Step 2 • start the server • you should see

    a message “Server is running on port: 3000” • go to “http://localhost:3000” in your browser. You should see “hi there” • stop the server $ node server.js
  22. Step 2 • we didn’t set process.env.PORT, so the port

    defaulted to to 3000. • to set the process.env.PORT, we pass in PORT • you should see a message “Server is running on port: 4000” • go to “http://localhost:4000” in your browser. $ PORT=4000 node server.js
  23. Step 2 • make the second commit $ git add

    . $ git commit -m ‘setup server and home route’
  24. Push to Github • Go to github. Create repo on

    Github by clicking on “+” in the upper right, and selecting “new repository” • give the repo a name and click “create repository” button
  25. Push to Github • look at the section called “…or

    push an existing repository from the command line” • connect your local repo to github by copying & pasting the 1st line • this adds a remote called ‘origin’ that points to the url of the repo ‘[email protected]:<username>/<repo>.git’ • https://git-scm.com/docs/git-remote $ git remote add origin [email protected]:<username>/<repo>.git
  26. Push to Github • push to the files to github

    • this pushes the ‘master’ branch to the remote ‘origin’ • -u tells git to remember origin and master branch for future pushes. The next time we push, we can use “git push”, and git will automatically use origin and master branch. • go to the github repo. you should see your files there. $ git push -u origin master
  27. What are templates? • in order for express to create

    html for the browser, it needs a templating engine • templating engine will take data, inject it into a template, and create the html • popular templating engines include jade, ejs, handlebars • we will use handlebars. • https://www.npmjs.com/package/express-handlebars
  28. What are layouts? • layouts are handlebars template files that

    contain html elements that you want to appear on every page, such as <head>, site navigation menus, etc • inside the layout file, there is {{{body}}} • {{{body}}} is where the other templates will be injected
  29. Step 3 • create a folder ‘views’ • create a

    folder ‘layouts’ inside of ‘views’ • create a file main.hbs and put it in ‘views/layouts’ • go the gist, and copy the contents of main.hbs into your local main.hbs
  30. Step 3 • main.hbs is our layout file. • it

    has links to Bootstrap (css framework) and Font Awesome (icon library), <head>, and the site navigate menu. • http://getbootstrap.com • http://fontawesome.io
  31. What is app.set? • app.set(<name>, <value>) • app.set is used

    to set configuration values for express • http://expressjs.com/en/4x/api.html#app.set
  32. Step 3 • we need to tell express the name

    of our folder that contains the views (aka templates). • the first ‘views’ tells express we are want to set the name of views folder. • the second ‘views’ tells express we want the views folder to be called ‘views’. var exphbs = require('express-handlebars'); var port = process.env.PORT || 3000; // ======================= // middleware & config // ======================= app.set('views', 'views'); server.js
  33. Step 3 • if we want the views folder to

    be called ‘templates’, we would do this app.set('views', 'templates');
  34. Step 3 • app.engine configures handlebars • to use .hbs

    as the extension, set the extname to ‘hbs' • to main.hbs as the default layout, set defaultLayout to ‘main’ • to specify the folder for the layouts, set layoutsDir to ‘./views/ layouts’ app.set('views', 'views'); app.engine('hbs', exphbs({ extname: 'hbs', defaultLayout: 'main', layoutsDir: './views/layouts' }));
  35. Step 3 • app.set('view engine', ‘hbs') tells express to use

    handlebars as the view engine app.engine('hbs', exphbs({ extname: 'hbs', defaultLayout: 'main', layoutsDir: './views/layouts' })); app.set('view engine', 'hbs');
  36. Step 3 • create template for the home page called

    home.hbs, and put it in ‘/views’ • add some html content such as <h1>Home Page</ h1>
  37. What is response.render? • response.render(‘template_name’, [data], [callback]) • response.render tells

    express to use a template. • we can optionally pass in some data and a callback. • http://expressjs.com/en/4x/api.html#res.render
  38. Step 3 • replace response.send(‘hi there’) with response.render • we

    are telling express to render ‘home’ template for the base route ‘/‘ • restart the server and go to localhost:3000. You should see the contents of home.hbs • the content is partially hidden by the nav; we will fix that later. app.get('/', function (request, response) { response.render(‘home’); });
  39. Step 3 • we pass data to the template as

    object. the object keys are the name of variables to use in the template • {title: ‘My Site’} sets the {{title}} in main.hbs to ‘My Site’ • Restart the server. You should see ‘My Site’ in the tab of your browser. app.get('/', function (request, response) { response.render(‘home’, { title: 'My Site' }); });
  40. Step 3 • make the another commit $ git add

    . $ git commit -m ‘add home page template’
  41. Step 4 • Students: create route for ‘/projects’ and create

    projects.hbs template. • add some html content to projects.hbs • pass in a title to the template. • when you visit http://localhost:3000/projects, you should see the contents of the projects template
  42. Step 4 • commit the changes $ git add .

    $ git commit -m ‘add projects route and template’
  43. Step 5 • create folder ‘/public’ and copy in styles.css

    from the gist into folder • ‘public’ will contain static assets files such as stylesheets, images, javascript files
  44. What is middleware? • express is a simple framework. it

    mainly does route matching • to add more functionality, we add middleware via app.use • middleware is executed on every request • http://expressjs.com/en/4x/api.html#app.use app.use()
  45. Step 5 • in order for express handle static files,

    we need to use the middleware express.static • express.static is the only middleware that express has built in • you pass in the location of the static assets folder app.set('view engine', 'hbs'); app.use(express.static('public'));
  46. Step 5 • restart the server. • express will load

    the stylesheet we just added. The styles for the homepage should be fixed. • commit the files $ git add . $ git commit -m ‘add styles’
  47. What is npm global install ? • use -g to

    install packages globally on your machine • globally installed packages can be accessed through command line • https://docs.npmjs.com/getting-started/installing- npm-packages-globally $ node install -g
  48. What is nodemon? • nodenom is node package that automatically

    restarts the server when a files changes • http://nodemon.io • install nodemon $ node install -g nodemon
  49. What is nodemon? • now instead of constantly restarting the

    server every time you make a change, nodemon will automatically restart the server when a change is made $ nodemon server.js
  50. Step 6 • we can pass in arrays to the

    templates • Students: create an array of your favorite things. It can be book, movies, songs, etc. Pass your list of favorites to the template. • in my example, I create an array of my favorite letters app.get('/', function (request, response) { var favoriteLetters = ['a', 'b', 'c']; response.render('home', { title: ‘My Site', favorites: favoriteLetters }); }); server.js
  51. Step 6 • in order to display the data in

    the templates add {{favorites}} to home.hbs • when you refresh the browser, you should see the list of your favorites <h1>My site</h1> {{ favorites }} My site a,b,c
  52. What is handlebars each? • handlebars provides {{#each}} {{/each}} to

    loop over each item in an array {{#each array_name as |item_in_array| }} {{item_in_array}} {{/each}}
  53. Step 6 • in order to create an unordered list

    of the favorites, use {{#each}} to loop through the favorites and add <li> tag to each item • favorites is the name of the variable we passed into the templates in server.js • favorite is a random variable we use to refer to each item in the array <h2>Favorite Letters</h2> <ul> {{#each favorites as |favorite| }} <li>{{favorite}}</li> {{/each}} </ul>
  54. Step 6 • commit the changes $ git add .

    $ git commit -m ‘add list of favorites to home’
  55. Step 7 • to create a list of links, we

    would pass an array of objects • each object has text and the url var favoriteLinks = [ { text: 'Apple', url: 'http://apple.com' }, { text: 'Facebook', url: 'http://facebook.com' } ]; response.render('home', { title: 'home page', favorites: favoriteLetters, links: favoriteLinks });
  56. Step 7 • in order to display the links in

    the templates add {{links}} to home.hbs {{#each links as |link| }} {{link}} {{/each}} [object Object] [object Object] • when you refresh the browser, you will see • • since each item is an object, handlebars renders the item as [object Object]
  57. Step 7 • in order to render an object, we

    need to access the url and text properties in the object <ul> {{#each links as |link| }} <li>{{link.url}} {{link.text}}</li> {{/each}} <ul> • when you refresh the browser, you should see the url and text for each link
  58. Step 7 • to display a list of clickable links,

    add <a> tag <h2>Favorite Links</h2> <ul> {{#each links as |link| }} <li><a href=“{{link.url}}”>{{link.text}}</a></li> {{/each}} <ul> • when you refresh the browser, you should a list of clickable links
  59. Step 7 • commit the changes • push to github

    $ git add . $ git commit -m ‘add list of links to home’ $ git push