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

Building web apps with Express

Andy Appleton
February 06, 2013

Building web apps with Express

An introduction to the Express web framework for Node.js

Andy Appleton

February 06, 2013
Tweet

More Decks by Andy Appleton

Other Decks in Technology

Transcript

  1. $ npm install -g express Init a new express app

    in ./awesome-demo $ express awesome-demo
  2. $ npm install -g express Install the app’s dependencies with

    npm $ express awesome-demo $ cd awesome-demo && npm install
  3. $ npm install -g express Run it! $ express awesome-demo

    $ cd awesome-demo && npm install $ node app.js >> Express server listening on port 3000
  4. // Get & set an app property app.set('name', 'value'); //

    Use a middleware function app.use(myMiddlewareFunction()); // Respond to an HTTP request app.get('/path', callbackFn); app.post('/path', callbackFn); app.put('/path', callbackFn); // ...etc
  5. Handling a route // /users routes.index = function(req, res) {

    res.send('Hello Bath'); }; // /users/:id routes.users.show = function(req, res) { var userId = req.params.id; res.send('Your userId is ' + userId); };
  6. Rendering HTML templates routes.index = function(req, res) { res.render('index'); };

    routes.users.show = function(req, res) { var userId = req.params.id; res.render('users/show', { id: userId }); };
  7. doctype 5 html head ... body block content extends layout

    block content h1= title p Welcome to #{title} ./views/layout.jade ./views/index.jade
  8. "dependencies": { ... "hbs": "*" } ./package.json $ npm install

    ./app.js app.configure(function(){ ... app.set('view engine', 'hbs'); ... }); app.configure(function(){ ... app.set('view engine', 'jade'); ... });
  9. routes.index = function(req, res) { res.render('index'); }; routes.users.show = function(req,

    res) { var userId = req.params.id; res.render('users/show', { id: userId }); };
  10. routes.users.show = function(req, res) { req.session.id || (req.session.id = 1);

    res.render('users/show', { id: req.session.id }); };