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

Fast Web Development with Express

Tommy Chen
November 06, 2014

Fast Web Development with Express

Tommy Chen

November 06, 2014
Tweet

More Decks by Tommy Chen

Other Decks in Programming

Transcript

  1. Hello World var express = require('express'); var app = express();

    app.get('/', function(req, res){ res.send('Hello world'); }); app.listen(4000, function(){ console.log('Server started!'); }); 3
  2. EJS app.set('views', __dirname + '/views'); app.set('view engine', 'html'); app.engine('html', require('ejs').renderFile);

    • EJS 是⼀一種 JavaScript 模版引擎 • 安裝:npm install ejs --save 11
  3. 模版 app.get('/users/:id', function(req, res, next){ res.render('users/show', {user: req.user}); }); 12

    My name is <%= user.name %> and I am <%= user.age %> years old. My name is Jack and I am 25 years old.
  4. 模版 - 陣列 13 My name is <%= user.name %>

    and I am <%= user.age %> years old. Here's my wishlist: <ul> <% user.wishlist.forEach(function(item){ %> <li><%= item %></li> <% }) %> </ul> My name is Jack and I am 25 years old. Here's my wish list: • iPhone 6 • Car
  5. Query string 14 http://localhost:4000/users/1?a=b&c=d • ? 後⾯面的字串即為 Query string •

    每個參數以 & 分隔 • key 和 value 以 = 分隔 • 在 Express 中使⽤用 req.query 讀取 Query string app.get('/', function(req, res){ console.log(req.query); });
  6. Body • Body 是 HTTP 請求的內容 • 使⽤用 body-parser 解析表單內容:npm

    install body-parser --save 15 app.use(require('body-parser').urlencoded({ extended: true }));