Save 37% off PRO during our Black Friday Sale! »

Workshop: Intro to Node/Express p1

Workshop: Intro to Node/Express p1

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

9785ceff83cfb7a1592ba89a51fbd444?s=128

Wai-Yin Kwan

April 29, 2016
Tweet

Transcript

  1. WWC Workshop: Intro to Node/Express

  2. Links • gist for extra files http://bit.ly/node_workshop • repo https://github.com/wykhuh/intro_node_live

  3. 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
  4. 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
  5. 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
  6. 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
  7. Step 1 • Goal: download express

  8. 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
  9. 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
  10. 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
  11. 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
  12. 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
  13. 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
  14. Step 1 • make the first commit $ git add

    . $ git commit -m ‘install express’
  15. Step 2 • Goal: create a server and add the

    base route
  16. 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) })
  17. 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');
  18. 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;
  19. 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) })
  20. 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
  21. 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
  22. Step 2 • add a base route var port =

    process.env.PORT || 3000; // ======================= // routes // ======================= app.get('/', function(request, response) { response.send('hi there'); })
  23. 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’); });
  24. 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’); });
  25. 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
  26. 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
  27. Step 2 • make the second commit $ git add

    . $ git commit -m ‘setup server and home route’
  28. 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
  29. 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 ‘git@github.com:<username>/<repo>.git’ • https://git-scm.com/docs/git-remote $ git remote add origin git@github.com:<username>/<repo>.git
  30. 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
  31. Step 3 • Goal: add templates for home page

  32. 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
  33. Step 3 • install handlebars $ npm install --save express-handlebars

  34. 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
  35. 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
  36. 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
  37. 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
  38. 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
  39. Step 3 • if we want the views folder to

    be called ‘templates’, we would do this app.set('views', 'templates');
  40. 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' }));
  41. 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');
  42. 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>
  43. 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
  44. 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’); });
  45. 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' }); });
  46. Step 3 • make the another commit $ git add

    . $ git commit -m ‘add home page template’
  47. 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
  48. Step 4 • commit the changes $ git add .

    $ git commit -m ‘add projects route and template’
  49. Step 5 • Goal: add a stylesheet

  50. 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
  51. 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()
  52. 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'));
  53. 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’
  54. 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
  55. 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
  56. 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
  57. Step 6 • Goal: add list of favorites to home

    page
  58. 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
  59. 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
  60. 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}}
  61. 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>
  62. Step 6 • commit the changes $ git add .

    $ git commit -m ‘add list of favorites to home’
  63. Step 7 • Goal: add list of favorites links to

    home page
  64. 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 });
  65. 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]
  66. 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
  67. 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
  68. Step 7 • commit the changes • push to github

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